Programs & Examples On #Du

du is a unix command to measure disk usage

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

python variable NameError

This should do it:

#!/usr/local/cpython-2.7/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print "\nHow much space should the random song list occupy?\n" print "1. 100Mb" print "2. 250Mb\n"  tSizeAns = int(raw_input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print "\nYou  want to create a random song list that is {}.".format(tSize) 

BTW, in case you're open to moving to Python 3.x, the differences are slight:

#!/usr/local/cpython-3.3/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print("\nHow much space should the random song list occupy?\n") print("1. 100Mb") print("2. 250Mb\n")  tSizeAns = int(input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print("\nYou want to create a random song list that is {}.".format(tSize)) 

HTH

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

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

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

This will be a JRE and JDK package.

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

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

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

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

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); 

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This is version problem, install the right dependant version

npm uninstall node-sass
npm install [email protected]

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

I realise this question is a little old, but the proposed answers are outdated/incorrect.

You should initially try to update both CocoaPods and the dependencies for your library/app, and then, if that doesn't work, contact the vendors of any dependencies you are using to see if they have an update in progress to add support for arm64 Simulator slices on M1 Macs.

There are a lot of answers on here marked as correct suggesting that you should exclude arm64 from the list of supported architectures. This is at best a very temporary workaround, and at worst it will spread this issue to other consumers of your libraries. If you exclude the arm64 Simulator slice, there will be performance impacts on apps that you're developing in the Simulator (which in turn can lead to reduced battery time for your shiny new M1 kit while you're developing your amazing ideas).

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Fixed it by opting out of Ivy as per documentation.

https://angular.io/guide/ivy

Change tsconfig.app.json to opt out of Ivy.

"enableIvy": false

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

TS1086: An accessor cannot be declared in ambient context

Setting "skipLibCheck": true in tsconfig.json solved my problem

"compilerOptions": {
    "skipLibCheck": true
}

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

@angular/material/index.d.ts' is not a module

@angular/material has changed its folder structure. Now you need to use all the modules from their respective folders instead of just material folder

For example:

import { MatDialogModule } from "@angular/material";

has now changed to

import { MatDialogModule } from "@angular/material/dialog";

You can check the following to find the correct path for your module

https://material.angular.io/components/categories

Just navigate to the API tab of required module and find the correct path like this 1

SyntaxError: Cannot use import statement outside a module

Step 1

yarn add esm

or

npm i esm --save

Step 2

package.json

  "scripts": {
    "start": "node -r esm src/index.js",
  }

Step 3

nodemon --exec npm start

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module" to both external as well as internal js scripts.

Say, you have a file 'module.js':

var a = 10;
export {a};

You can use it in an external script, in which you do the import, eg.:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

test.js:

import {a} from "./module.js";
alert(a);

You can also use it in an internal script, eg.:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:

import {a} from "module.js";     // this won't work

How to resolve the error on 'react-native start'

You have two solutions:

either you downgrade node to V12.10.0 or you can modify this file for every project you will create.

node_modules/metro-config/src/defaults/blacklist.js Change this:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

to this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Unable to allocate array with shape and data type

I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.

Windows 8

  1. On the Keyboard Press the WindowsKey + X then click System in the popup menu
  2. Tap or click Advanced system settings. You might be asked for an admin password or to confirm your choice
  3. On the Advanced tab, under Performance, tap or click Settings.
  4. Tap or click the Advanced tab, and then, under Virtual memory, tap or click Change
  5. Clear the Automatically manage paging file size for all drives check box.
  6. Under Drive [Volume Label], tap or click the drive that contains the paging file you want to change
  7. Tap or click Custom size, enter a new size in megabytes in the initial size (MB) or Maximum size (MB) box, tap or click Set, and then tap or click OK
  8. Reboot your system

Windows 10

  1. Press the Windows key
  2. Type SystemPropertiesAdvanced
  3. Click Run as administrator
  4. Under Performance, click Settings
  5. Select the Advanced tab
  6. Select Change...
  7. Uncheck Automatically managing paging file size for all drives
  8. Then select Custom size and fill in the appropriate size
  9. Press Set then press OK then exit from the Virtual Memory, Performance Options, and System Properties Dialog
  10. Reboot your system

Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.

EDIT

From here the suggested recommendations for page file size:

There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.

Some things to keep in mind from here:

However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.

Also:

Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.

How to prevent Google Colab from disconnecting?

function ClickConnect()
{
    console.log("Working...."); 
    document.querySelector("paper-button#comments").click()
}
setInterval(ClickConnect,600)

this worked for me but use wisely

happy learning :)

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

You can change the matplotlib using backend using the from agg to Tkinter TKAgg using command

matplotlib.use('TKAgg',warn=False, force=True)

How to style components using makeStyles and still have lifecycle methods in Material UI?

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        root: {
            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            border: 0,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            padding: '0 30px',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

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

Following actions worked for me.

1.Go to Project in toolbar -> Unchecked "Build Automatically"

2.In POM File,Downgrade the spring-boot version to 2.1.4 RELEASE.

3.Right Click on Project name -> Select Maven -> Click on "Update Project". ->OK Wait till all the maven dependency to get downloaded(Need internet).

How to fix ReferenceError: primordials is not defined in node

Using NVM to manage what node version you're using, running the following commands worked for me:

$ cd /to/your/project/
$ nvm install lts/dubnium
$ nvm use lts/dubnium
$ yarn upgrade # or `npm install`

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

The error also can occur if you try to save a python list of numpy arrays with np.save and load with np.load. I am only saying it for the sake of googler's to check out that this is not the issue. Also using allow_pickle=True fixed the issue if a list is indeed what you meant to save and load.

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Module 'tensorflow' has no attribute 'contrib'

I used google colab to run my models and everything was perfect untill i used inline tesorboard. With tensorboard inline, I had the same issue of "Module 'tensorflow' has no attribute 'contrib'".

It was able to run training when rebuild and reinstall the model using setup.py(research folder) after initialising tensorboard.

How to fix missing dependency warning when using useEffect React Hook?

const [mount, setMount] = useState(false)
const fetchBusinesses = () => { 
   //function defination
}
useEffect(() => {
   if(!mount) {
      setMount(true);
      fetchBusinesses();
   }
},[fetchBusinesses]);

This is solution is pretty simple and you don't need to override es-lint warnings. Just maintain a flag to check whether component is mounted or not.

React Native Error: ENOSPC: System limit for number of file watchers reached

Linux uses the inotify package to observe filesystem events, individual files or directories.

Since React / Angular hot-reloads and recompiles files on save it needs to keep track of all project's files. Increasing the inotify watch limit should hide the warning messages.

You could try editing

# insert the new value into the system config
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

# check that the new value was applied
cat /proc/sys/fs/inotify/max_user_watches

# config variable name (not runnable)
fs.inotify.max_user_watches=524288

How to update core-js to core-js@3 dependency?

You update core-js with the following command:

npm install --save core-js@^3

If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

None of the above helped for me.

I was able to install Mojave using this link here: http://dosdude1.com/mojave/ This patch worked beautifully and without a hitch

Proof: here's Mojave running on my (unsupported) 2011 Mac-mini

Module not found: Error: Can't resolve 'core-js/es6'

Make changes to your Polyfills.ts file

Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts

How to set value to form control in Reactive Forms in Angular

The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup

createFormGroup(data:any)
{
 return this.fb.group({
   user: [data?data.user:null],
   questioning: [data?data.questioning:null, Validators.required],
   questionType: [data?data.questionType, Validators.required],
   options: new FormArray([this.createArray(data?data.options:null])
})
}

//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
   return data.map(x=>this.fb.group({
        ....
   })
}

then, in SUBSCRIBE, you call the function

this.qService.editQue([params["id"]]).subscribe(res => {
  this.editqueForm = this.createFormGroup(res);
});

be carefull!, your form must include an *ngIf to avoid initial error

<form *ngIf="editqueForm" [formGroup]="editqueForm">
   ....
</form>

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

In SnackbarContentWrapper you need to change

<IconButton
          key="close"
          aria-label="Close"
          color="inherit"
          className={classes.close}
          onClick={onClose}
        >

to

<IconButton
          key="close"
          aria-label="Close"
          color="inherit"
          className={classes.close}
          onClick={() => onClose}
        >

so that it only fires the action when you click.

Instead, you could just curry the handleClose in SingInContainer to

const handleClose = () => (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

It's the same.

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

If you don't have cocoa pods installed you need to:

sudo gem install cocoapods

Then run:

cd /ios
pod install

delete the build folder in ios folder of your react native project

run:

react-native run-ios

if error persists:

  • delete build folder again
  • open the /ios folder in Xcode
  • navigate File -> Project Settings -> Build System -> change (Shared workspace settings and Per-User workspace settings): Build System -> Legacy Build System

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

I just ran into the same kind of error using RSelenium::rsDriver()'s default chromever = "latest" setting which resulted in the failed attempt to combine chromedriver 75.0.3770.8 with latest google-chrome-stable 74.0.3729.157:

session not created: This version of ChromeDriver only supports Chrome version 75

Since this obviously seems to be a recurring and pretty annoying issue, I have come up with the following workaround to always use the latest compatible ChromeDriver version:

rD <- RSelenium::rsDriver(browser = "chrome",
                          chromever =
                                  system2(command = "google-chrome-stable",
                                          args = "--version",
                                          stdout = TRUE,
                                          stderr = TRUE) %>%
                                  stringr::str_extract(pattern = "(?<=Chrome )\\d+\\.\\d+\\.\\d+\\.") %>%
                                  magrittr::extract(!is.na(.)) %>%
                                  stringr::str_replace_all(pattern = "\\.",
                                                           replacement = "\\\\.") %>%
                                  paste0("^",  .) %>%
                                  stringr::str_subset(string =
                                                              binman::list_versions(appname = "chromedriver") %>%
                                                              dplyr::last()) %>%
                                  as.numeric_version() %>%
                                  max() %>%
                                  as.character())

The above code is only tested under Linux and makes use of some tidyverse packages (install them beforehand or rewrite it in base R). For other operating systems you might have to adapt it a bit, particularly replace command = "google-chrome-stable" with the system-specific command to launch Google Chrome:

  • On macOS it should be enough to replace command = "google-chrome-stable" with command = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".

  • On Windows a plattform-specific bug prevents us from calling the Google Chrome binary directly to get its version number. Instead do the following:

    rD <- RSelenium::rsDriver(browser = "chrome",
                              chromever =
                                system2(command = "wmic",
                                        args = 'datafile where name="C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe" get Version /value',
                                        stdout = TRUE,
                                        stderr = TRUE) %>%
                                stringr::str_extract(pattern = "(?<=Version=)\\d+\\.\\d+\\.\\d+\\.") %>%
                                magrittr::extract(!is.na(.)) %>%
                                stringr::str_replace_all(pattern = "\\.",
                                                         replacement = "\\\\.") %>%
                                paste0("^",  .) %>%
                                stringr::str_subset(string =
                                                            binman::list_versions(appname = "chromedriver") %>%
                                                            dplyr::last()) 
                                as.numeric_version() %>%
                                max() %>%
                                as.character())
    

Basically, the code just ensures the latest ChromeDriver version matching the major-minor-patch version number of the system's stable Google Chrome browser is passed as chromever argument. This procedure should adhere to the official ChromeDriver versioning scheme. Quote:

  • ChromeDriver uses the same version number scheme as Chrome (...)
  • Each version of ChromeDriver supports Chrome with matching major, minor, and build version numbers. For example, ChromeDriver 73.0.3683.20 supports all Chrome versions that start with 73.0.3683.

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

try this

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello))

react hooks useEffect() cleanup for only componentWillUnmount?

instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.

//componentDidMount
useEffect( () => {

    window.addEventListener("load",  pageLoad);

    //component will unmount
    return () => {
       
        window.removeEventListener("load", pageLoad);
    }

 });

now that this part is done I just run anything I want from the pageLoad function like this.

const pageLoad = () =>{
console.log(I was mounted and unmounted automatically :D)}

How to Install pip for python 3.7 on Ubuntu 18?

To install all currently supported python versions (python 3.6 is already pre-installed) including pip for Ubuntu 18.04 do the following:

To install python3.5 and python3.7, use the deadsnakes ppa:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5
sudo apt-get install python3.7

Install python2.7 via distribution packages:

sudo apt install python-minimal  # on Ubuntu 18.04 python-minimal maps to python2.7

To install pip use:

sudo apt install python-pip  # on Ubuntu 18.04 this refers to pip for python2.7
sudo apt install python3-pip  # on Ubuntu 18.04 this refers to pip for python3.6
python3.5 -m pip install pip # this will install pip only for the current user
python3.7 -m pip install pip

I used it for setting up a CI-chain for a python project with tox and Jenkins.

Flutter Countdown Timer

You can use this plugin timer_builder

timer_builder widget that rebuilds itself on scheduled, periodic, or dynamically generated time events.

Examples

Periodic rebuild

import 'package:timer_builder/timer_builder.dart';

class ClockWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return TimerBuilder.periodic(Duration(seconds: 1),
      builder: (context) {
        return Text("${DateTime.now()}");
      }
    );
  }
  
}

Rebuild on a schedule

import 'package:timer_builder/timer_builder.dart';

class StatusIndicator extends StatelessWidget {

  final DateTime startTime;
  final DateTime endTime;
  
  StatusIndicator(this.startTime, this.endTime);
  
  @override
  Widget build(BuildContext context) {
    return TimerBuilder.scheduled([startTime, endTime],
      builder: (context) {
        final now = DateTime.now();
        final started = now.compareTo(startTime) >= 0;
        final ended = now.compareTo(endTime) >= 0;
        return Text(started ? ended ? "Ended": "Started": "Not Started");
      }
    );
  }
  
}

enter image description here

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

For those newbies like me, don't assign variable to service response, meaning do

export class ShopComponent implements OnInit {
  public productsArray: Product[];

  ngOnInit() {
      this.productService.getProducts().subscribe(res => {
        this.productsArray = res;
      });
  }
}

Instead of

export class ShopComponent implements OnInit {
    public productsArray: Product[];

    ngOnInit() {
        this.productsArray = this.productService.getProducts().subscribe();
    }
}

"Failed to install the following Android SDK packages as some licences have not been accepted" error

MacOS Catalina

Step 1: Changing Android Studio Preference

  1. Open-up your Android Studio
  2. Press Command+, or go to top-left AppBar Android Studio > Preferences.
  3. From Left Pane, select Appearance > System Settings > Android SDK
  4. Select SDK Tools next to SDK Platforms and under Android SDK Location
  5. Check mark Android SDK Command-line Tools (latest) and Press OK button.
  6. Wait for installation to be finished

Locating Preferences of Android Studio

Android Studio Preferences

Step 2 (For Flutter Users):

  1. Go to Terminal and run the following command

flutter doctor --android-licenses

Step 2 (For Android Users):

  1. Go to the Terminal and run the following command

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home

yes | ~/Library/Android/sdk/tools/bin/sdkmanager --licenses

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

2021 Jan.12th

the whole point for me is to explicitly specify the version as java 11 in my pom.xml, and I solved the problem by taking the following steps.

  1. open terminal and input: java -version, then i got 1.8, and i went to .bash_profile to switch the java version to 11.2 as i have multiple java version installed. please remember "restart" your terminal and check your java version again to confirm switch is successful.

  2. Then i went to File -> Project Structure to make sure my IntelliJ using the same version as my env, which is 11.2.

  3. RESTART your Intellij, mvn clean install, solved, hope this could help someone with this issue, thanks.

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I am on Windows 10, I had the problem with a new fresh installation of Anaconda on python 3.7.4, this post on github solved my problem:

( source: https://github.com/conda/conda/issues/8273)

I cite:

" My workaround: I have copied the following files

libcrypto-1_1-x64.*
libssl-1_1-x64.*

from D:\Anaconda3\Library\bin to D:\Anaconda3\DLLs.

And it works as a charm! "

useState set method not reflecting change immediately

Additional details to the previous answer:

While React's setState is asynchronous (both classes and hooks), and it's tempting to use that fact to explain the observed behavior, it is not the reason why it happens.

TLDR: The reason is a closure scope around an immutable const value.


Solutions:

  • read the value in render function (not inside nested functions):

      useEffect(() => { setMovies(result) }, [])
      console.log(movies)
    
  • add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):

      useEffect(() => { setMovies(result) }, [])
      useEffect(() => { console.log(movies) }, [movies])
    
  • use a mutable reference (when the above is not possible):

      const moviesRef = useRef(initialValue)
      useEffect(() => {
        moviesRef.current = result
        console.log(moviesRef.current)
      }, [])
    

Explanation why it happens:

If async was the only reason, it would be possible to await setState().

However, both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

With hooks, this assumption is enhanced by using constant values with the const keyword:

const [state, setState] = useState('initial')

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

Consider following fake, but synchronous, React-like implementation:

_x000D_
_x000D_
// sync implementation:

let internalState
let renderAgain

const setState = (updateFn) => {
  internalState = updateFn(internalState)
  renderAgain()
}

const useState = (defaultState) => {
  if (!internalState) {
    internalState = defaultState
  }
  return [internalState, setState]
}

const render = (component, node) => {
  const {html, handleClick} = component()
  node.innerHTML = html
  renderAgain = () => render(component, node)
  return handleClick
}

// test:

const MyComponent = () => {
  const [x, setX] = useState(1)
  console.log('in render:', x) // ?
  
  const handleClick = () => {
    setX(current => current + 1)
    console.log('in handler/effect/Promise/setTimeout:', x) // ? NOT updated
  }
  
  return {
    html: `<button>${x}</button>`,
    handleClick
  }
}

const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

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

Based on @ford04 answer, here is the same encapsulated in a method :

import React, { FC, useState, useEffect, DependencyList } from 'react';

export function useEffectAsync( effectAsyncFun : ( isMounted: () => boolean ) => unknown, deps?: DependencyList ) {
    useEffect( () => {
        let isMounted = true;
        const _unused = effectAsyncFun( () => isMounted );
        return () => { isMounted = false; };
    }, deps );
} 

Usage:

const MyComponent : FC<{}> = (props) => {
    const [ asyncProp , setAsyncProp ] = useState( '' ) ;
    useEffectAsync( async ( isMounted ) =>
    {
        const someAsyncProp = await ... ;
        if ( isMounted() )
             setAsyncProp( someAsyncProp ) ;
    });
    return <div> ... ;
} ;

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

Issue has been resolved after updating Android studio version to 3.3-rc2 or latest released version.

cr: @shadowsheep

have to change version under /gradle/wrapper/gradle-wrapper.properties. refer below url https://stackoverflow.com/a/56412795/7532946

internal/modules/cjs/loader.js:582 throw err

I was having the same error because I had a space at the end of my filename(not the reference but the actual filename). Once I changed 'app.js ' to 'app.js' it worked fine.

How to use componentWillMount() in React Hooks?

According to reactjs.org, componentWillMount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

There is no need to use componentWillMount.

If you want to do something before the component mounted, just do it in the constructor().

If you want to do network requests, do not do it in componentWillMount. It is because doing this will lead to unexpected bugs.

Network requests can be done in componentDidMount.

Hope it helps.


updated on 08/03/2019

The reason why you ask for componentWillMount is probably because you want to initialize the state before renders.

Just do it in useState.

const helloWorld=()=>{
    const [value,setValue]=useState(0) //initialize your state here
    return <p>{value}</p>
}
export default helloWorld;

or maybe You want to run a function in componentWillMount, for example, if your original code looks like this:

componentWillMount(){
  console.log('componentWillMount')
}

with hook, all you need to do is to remove the lifecycle method:

const hookComponent=()=>{
    console.log('componentWillMount')
    return <p>you have transfered componeWillMount from class component into hook </p>
}

I just want to add something to the first answer about useEffect.

useEffect(()=>{})

useEffect runs on every render, it is a combination of componentDidUpdate, componentDidMount and ComponentWillUnmount.

 useEffect(()=>{},[])

If we add an empty array in useEffect it runs just when the component mounted. It is because useEffect will compare the array you passed to it. So it does not have to be an empty array.It can be array that is not changing. For example, it can be [1,2,3] or ['1,2']. useEffect still only runs when component mounted.

It depends on you whether you want it to run just once or runs after every render. It is not dangerous if you forgot to add an array as long as you know what you are doing.

I created a sample for hook. Please check it out.

https://codesandbox.io/s/kw6xj153wr


updated on 21/08/2019

It has been a while since I wrote the above answer. There is something that I think you need to pay attention to. When you use

useEffect(()=>{},[])

When react compares the values you passed to the array [], it uses Object.is() to compare. If you pass an object to it, such as

useEffect(()=>{},[{name:'Tom'}])

This is exactly the same as:

useEffect(()=>{})

It will re-render every time because when Object.is() compares an object, it compares its reference, not the value itself. It is the same as why {}==={} returns false because their references are different. If you still want to compare the object itself not the reference, you can do something like this:

useEffect(()=>{},[JSON.stringify({name:'Tom'})])

How to compare oldValues and newValues on React Hooks useEffect?

Using Ref will introduce a new kind of bug into the app.

Let's see this case using usePrevious that someone commented before:

  1. prop.minTime: 5 ==> ref.current = 5 | set ref.current
  2. prop.minTime: 5 ==> ref.current = 5 | new value is equal to ref.current
  3. prop.minTime: 8 ==> ref.current = 5 | new value is NOT equal to ref.current
  4. prop.minTime: 5 ==> ref.current = 5 | new value is equal to ref.current

As we can see here, we are not updating the internal ref because we are using useEffect

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

Restart worked for me... Mac OS restart, not xCode restart...

What is the meaning of "Failed building wheel for X" in pip install?

I had the same problem while installing Brotli

ERROR

Failed building wheel for Brotli

I solved it by downloading the .whl file from here and installing it using the below command

C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl

must declare a named package eclipse because this compilation unit is associated to the named module

Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.

Quick fix:

  1. Create a package eg. helloWorld inside the src folder.
  2. Move helloWorld.java file in that package. Just drag and drop on the package. Error should disappear.

Explanation:

  • My Eclipse version: 2020-09 (4.17.0)
  • My Java version: Java 15, 2020-09-15

Latest version of Eclipse required java11 or above. The module feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules

When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java file. If you select don't create then module-info.java will not create and your project will free from this issue.

Best practice is while crating project, after giving project name. Click on next button instead of finish. On next page at the bottom it ask for creation of module-info.java file. Select or deselect as per need.

If selected: (by default) click on finish button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.

If deselect: No issue

Could not install packages due to an EnvironmentError: [Errno 13]

I also had the same problem, I tried many different command lines, this one worked for me:

Try:

    conda install py-xgboost

That's what I got:

Collecting package metadata: done
Solving environment: done

## Package Plan ##

  environment location: /home/simplonco/anaconda3

  added / updated specs:
    - py-xgboost


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _py-xgboost-mutex-2.0      |            cpu_0           9 KB
    ca-certificates-2019.1.23  |                0         126 KB
    certifi-2018.11.29         |           py37_0         146 KB
    conda-4.6.2                |           py37_0         1.7 MB
    libxgboost-0.80            |       he6710b0_0         3.7 MB
    mkl-2019.1                 |              144       204.6 MB
    mkl_fft-1.0.10             |   py37ha843d7b_0         169 KB
    mkl_random-1.0.2           |   py37hd81dba3_0         405 KB
    numpy-1.15.4               |   py37h7e9f1db_0          47 KB
    numpy-base-1.15.4          |   py37hde5b4d6_0         4.2 MB
    py-xgboost-0.80            |   py37he6710b0_0         1.7 MB
    scikit-learn-0.20.2        |   py37hd81dba3_0         5.7 MB
    scipy-1.2.0                |   py37h7c811a0_0        17.7 MB
    ------------------------------------------------------------
                                           Total:       240.0 MB

The following NEW packages will be INSTALLED:

  _py-xgboost-mutex  pkgs/main/linux-64::_py-xgboost-mutex-2.0-cpu_0
  libxgboost         pkgs/main/linux-64::libxgboost-0.80-he6710b0_0
  py-xgboost         pkgs/main/linux-64::py-xgboost-0.80-py37he6710b0_0

The following packages will be UPDATED:

  ca-certificates     anaconda::ca-certificates-2018.12.5-0 --> pkgs/main::ca-certificates-2019.1.23-0
  mkl                                            2019.0-118 --> 2019.1-144
  mkl_fft                              1.0.4-py37h4414c95_1 --> 1.0.10-py37ha843d7b_0
  mkl_random                           1.0.1-py37h4414c95_1 --> 1.0.2-py37hd81dba3_0
  numpy                               1.15.1-py37h1d66e8a_0 --> 1.15.4-py37h7e9f1db_0
  numpy-base                          1.15.1-py37h81de0dd_0 --> 1.15.4-py37hde5b4d6_0
  scikit-learn                        0.19.2-py37h4989274_0 --> 0.20.2-py37hd81dba3_0
  scipy                                1.1.0-py37hfa4b5c9_1 --> 1.2.0-py37h7c811a0_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                          anaconda --> pkgs/main
  conda                                            anaconda --> pkgs/main
  openssl                anaconda::openssl-1.1.1-h7b6447c_0 --> pkgs/main::openssl-1.1.1a-h7b6447c_0


Proceed ([y]/n)? y


Downloading and Extracting Packages
libxgboost-0.80      | 3.7 MB    | ##################################### | 100% 
mkl_random-1.0.2     | 405 KB    | ##################################### | 100% 
certifi-2018.11.29   | 146 KB    | ##################################### | 100% 
ca-certificates-2019 | 126 KB    | ##################################### | 100% 
conda-4.6.2          | 1.7 MB    | ##################################### | 100% 
mkl-2019.1           | 204.6 MB  | ##################################### | 100% 
mkl_fft-1.0.10       | 169 KB    | ##################################### | 100% 
numpy-1.15.4         | 47 KB     | ##################################### | 100% 
scipy-1.2.0          | 17.7 MB   | ##################################### | 100% 
scikit-learn-0.20.2  | 5.7 MB    | ##################################### | 100% 
py-xgboost-0.80      | 1.7 MB    | ##################################### | 100% 
_py-xgboost-mutex-2. | 9 KB      | ##################################### | 100% 
numpy-base-1.15.4    | 4.2 MB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget

 Expanded(child:MyListView())

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

OpenCV !_src.empty() in function 'cvtColor' error

In my case it was a permission issue. I had to:

  • chmod a+wrx the image,

then it worked.

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

Change your Google Services version from your build.gradle:

dependencies {
  classpath 'com.google.gms:google-services:4.2.0'
}

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Problems after upgrading to Xcode 10: Build input file cannot be found

This worked for me in Xcode 10:

  • Click Project icon/name in your Xcode project
  • Go to General tab
  • Click [Choose info.plist File] under Identity section
  • Select the info.Plist file
  • Check Info tab to see if info.plist was loaded successfully
  • Build and run

GoogleMaps API KEY for testing

Updated Answer

As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.

This answer is no longer valid

As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.

Support for the experimental syntax 'classProperties' isn't currently enabled

Solution for webpack project

I just solve this problem by adding @babel/plugin-proposal-class-properties into webpack config plugin. The module section of my webpack.config.js looks like this

module: {
    rules: [
        {
            test: path.join(__dirname, '.'),
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env',
                          '@babel/react',{
                          'plugins': ['@babel/plugin-proposal-class-properties']}]
            }
        }
    ]
}

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');

Change this line from your code to this -

var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');

or in my case, I gave the encoding in reverse order

var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');

Flutter - The method was called on null

As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.

For example: Assume we have double _bmi; and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:

String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}

or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

As it is mentioned in the error that there is no --user so you have to follow these steps

  1. Open cmd or anaconda Navigator
  2. Open your python install directory(For anaconda navigator you have specify the path like C:/cd Anaconda
  3. Then last is to python -m pip install --user somepackagename

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

so i change the TAGS "domain-config" for "base-config" and works, like this:

<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </base-config>
</network-security-config>

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

28.0.0 is the final version of support libraries. Android has migrated to AndroidX. To use the latest android libraries, Migrating to AndroidX


Edit: Versions 28.0.0-rc02 and 28.0.0 are now available.

I don't see any 28.0 version on Google Maven. Only 28.0.0-alpha1 and 28.0.0-alpha3. Just change it to either of those or how it was previously, i.e., with .+ which just means any version under 28 major release.

For an alpha appcompat release 28.+ makes more sense.

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?

I accepted trebleCode's answer, but I wanted to provide a bit more detail regarding the steps I took to install the nupkg of interest pswindowsupdate.2.0.0.4.nupkg on my unconnected Win 7 machine by way of following trebleCode's answer.

First: after digging around a bit, I think I found the MS docs that trebleCode refers to:

Bootstrap the NuGet provider and NuGet.exe

Install-PackageProvider

To continue, as trebleCode stated, I did the following

Install NuGet provider on my connected machine

On a connected machine (Win 10 machine), from the PS command line, I ran Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force. The Nuget software was obtained from the 'Net and installed on my local connected machine.

After the install I found the NuGet provider software at C:\Program Files\PackageManagement\ProviderAssemblies (Note: the folder name \ProviderAssemblies as opposed to \ReferenceAssemblies was the one minor difference relative to trebleCode's answer.

The provider software is in a folder structure like this:

C:\Program Files\PackageManagement\ProviderAssemblies
   \NuGet
      \2.8.5.208
         \Microsoft.PackageManagement.NuGetProvider.dll

Install NuGet provider on my unconnected machine

I copied the \NuGet folder (and all its children) from the connected machine onto a thumb drive and copied it to C:\Program Files\PackageManagement\ProviderAssemblies on my unconnected (Win 7) machine

I started PS (v5) on my unconnected (Win 7) machine and ran Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current PowerShell session.

I ran Get-PackageProvider -ListAvailable and saw this (NuGet appears where it was not present before):

Name                     Version          DynamicOptions                                                                                                                                                                      
----                     -------          --------------                                                                                                                                                                      
msi                      3.0.0.0          AdditionalArguments                                                                                                                                                                 
msu                      3.0.0.0                                                                                                                                                                                              
NuGet                    2.8.5.208        Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrereleaseVersions, ConfigFile, SkipValidate                                             
PowerShellGet            1.0.0.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPathUpdate, Filter, Tag, Includes, DscResource, RoleCapability, Command, PublishLocati...
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent

Create local repository on my unconnected machine

On unconnected (Win 7) machine, I created a folder to serve as my PS repository (say, c:\users\foo\Documents\PSRepository)

I registered the repo: Register-PSRepository -Name fooPsRepository -SourceLocation c:\users\foo\Documents\PSRepository -InstallationPolicy Trusted

Install the NuGet package

I obtained and copied the nupkg pswindowsupdate.2.0.0.4.nupkg to c:\users\foo\Documents\PSRepository on my unconnected Win7 machine

I learned the name of the module by executing Find-Module -Repository fooPsRepository

Version    Name                                Repository           Description                                                                                                                      
-------    ----                                ----------           -----------                                                                                                                      
2.0.0.4    PSWindowsUpdate                     fooPsRepository      This module contain functions to manage Windows Update Client.

I installed the module by executing Install-Module -Name pswindowsupdate

I verified the module installed by executing Get-Command –module PSWindowsUpdate

CommandType     Name                                               Version    Source                                                                                                                 
-----------     ----                                               -------    ------                                                                                                                 
Alias           Download-WindowsUpdate                             2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Get-WUInstall                                      2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Get-WUList                                         2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Hide-WindowsUpdate                                 2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Install-WindowsUpdate                              2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Show-WindowsUpdate                                 2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           UnHide-WindowsUpdate                               2.0.0.4    PSWindowsUpdate                                                                                                        
Alias           Uninstall-WindowsUpdate                            2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Add-WUServiceManager                               2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Enable-WURemoting                                  2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WindowsUpdate                                  2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUApiVersion                                   2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUHistory                                      2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUInstallerStatus                              2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUJob                                          2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WULastResults                                  2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WURebootStatus                                 2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUServiceManager                               2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUSettings                                     2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Get-WUTest                                         2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Invoke-WUJob                                       2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Remove-WindowsUpdate                               2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Remove-WUServiceManager                            2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Set-WUSettings                                     2.0.0.4    PSWindowsUpdate                                                                                                        
Cmdlet          Update-WUModule                                    2.0.0.4    PSWindowsUpdate 

I think I'm good to go

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

Complementing @lasse-v-karlsen answer. To unblock all files recursively, run from powershell as administrator inside the folder you want:

gci -recurse | Unblock-File

source link: How to Unblock Files Downloaded from Internet? - Winhelponline
https://www.winhelponline.com/blog/bulk-unblock-files-downloaded-internet/

How to resolve TypeError: can only concatenate str (not "int") to str

Use this:

print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
    sum += number
print("Total Sum is: %d" %sum )

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

This link helped.

Spring Boot auto-configuration tries to configure beans automatically based on the dependencies added to the classpath. And because we have a JPA dependency (spring-data-starter-jpa) on our classpath, it tries to configure it.

The problem: Spring boot doesn't have the all the info needed to configure the JPA data source i.e. the JDBC connection properties. Solutions:

  1. provide the JDBC connection properties (best)
  2. postpone supplying connection properties by excluding some AutoConfig classes (temporary - should be removed eventually)

The above link excludes the DataSourceAutoConfiguration.class with

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

But this didn't work for me. I instead, had to exclude 2 AutoConfig classes:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class})

Sort Array of object by object field in Angular 6

Not tested but should work

 products.sort((a,b)=>a.title.rendered > b.title.rendered)

Flask at first run: Do not use the development server in a production environment

If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run

$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run

Alternatively you can do the following (I haven't tried this but one resource online talks about it)

$ export FLASK_APP = hello.py
$ python -m flask run

source: For more

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

I too had to face the same problem. This worked for me. Right click and run as admin than run usual command to install. But first run update command to update the pip

python -m pip install --upgrade pip

Angular 6: How to set response type as text while making http call

By Default angular return responseType as Json, but we can configure below types according to your requirement.

responseType: 'arraybuffer'|'blob'|'json'|'text'

Ex:

this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'});

Xcode 10 Error: Multiple commands produce

Moving to Xcode 10, errors like

error: Multiple commands produce '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist':

can be solved as follows:

Go to Xcode->File->Workspace/Project Settings-> Build System -> Legacy Build System.

phpMyAdmin - Error > Incorrect format parameter?

If you can't upload import file due to big size and you can't modify parameters because you are in a shared hosting try to install on your computer HeidiSQL and load file from there.

How do I resolve a TesseractNotFoundError?

Under Windows 10 OS environment, the following method works for me:

  1. https://github.com/tesseract-ocr/tesseract/wiki Download tesseract and install it. Windows version is available here: https://github.com/UB-Mannheim/tesseract/wiki

  2. Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it. Change the following code from tesseract_cmd = 'tesseract' to: tesseract_cmd = 'D:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

  3. You may also need add environment variable D:/Program Files (x86)/Tesseract-OCR/

Hope it works for you!

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

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

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

Can not find module “@angular-devkit/build-angular”

Run the below command to get it resolved. Whenever you pull a new project, few dependencies wont get added to the working directory. Run the below command to get it resolved

npm install --save-dev @angular-devkit/build-angular

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

Could not find module "@angular-devkit/build-angular"

Following commands works:

npm install
ng update

-You may see the message "We analyzed your package.json and everything seems to be in order. Good work!"

npm update

Then try dev build

ng build 

I got the error with type script, downgraded to

npm install typescript@">=3.1.1 <3.2

ng build --prod 

All success with prod build.

Below is the working combination

ng --version

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.0
@angular-devkit/build-angular     0.11.0
@angular-devkit/build-optimizer   0.11.0
@angular-devkit/build-webpack     0.11.0
@angular-devkit/core              7.1.0
@angular-devkit/schematics        7.1.0
@angular/cli                      7.1.0
@ngtools/webpack                  7.1.0
@schematics/angular               7.1.0
@schematics/update                0.11.0
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.23.1

How to add bootstrap in angular 6 project?

using command

npm install bootstrap --save

open .angular.json old (.angular-cli.json ) file find the "styles" add the bootstrap css file

"styles": [
       "src/styles.scss",
       "node_modules/bootstrap/dist/css/bootstrap.min.css"
],

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I had this problem during migration to Spring Boot. I've found a advice to remove dependencies and it helped. So, I removed dependency for jsp-api Project had. Also, servlet-api dependency has to be removed as well.

compileOnly group: 'javax.servlet.jsp', name: 'jsp-api', version: '2.2' 

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Check privileges and username/password for your MySQL user.

For catching errors it is always useful to use overrided _delegateError method. In your case this has to look like:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  insecureAuth : true
});

var _delegateError = con._protocol._delegateError;

con._protocol._delegateError = function(err, sequence) {
    if (err.fatal)
        console.trace('MySQL fatal error: ' + err.message);

    return _delegateError.call(this, err, sequence);
};

con.connect(function(err) {
  if (err) throw err;

  console.log("Connected!");
});

This construction will help you to trace fatal errors.

Arduino IDE can't find ESP8266WiFi.h file

When programming the NODEMCU card with the Arduino IDE, you need to customize it and you must have selected the correct card.

Open Arduino IDE and go to files and click on the preference in the Arduino IDE.

Add the following link to the Additional Manager URLS section: "http://arduino.esp8266.com/stable/package_esp8266com_index.json" and press the OK button.

Then click Tools> Board Manager. Type "ESP8266" in the text box to search and install the ESP8266 software for Arduino IDE.

You will be successful when you try to program again by selecting the NodeMCU card after these operations. I hope I could help.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

provide all custom services means written by you in component decorator section Example : providers: [serviceName]

note:if you are using service for exchanging data between components. declare providers: [serviceName] in module level

Importing json file in TypeScript

Another way to go

const data: {[key: string]: any} = require('./data.json');

This was you still can define json type is you want and don't have to use wildcard.

For example, custom type json.

interface User {
  firstName: string;
  lastName: string;
  birthday: Date;
}
const user: User = require('./user.json');

pip: no module named _internal

In file "/usr/local/bin/pip" change from pip._internal import main to from pip import main

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

I experienced this when upgrading .NET Core 1.1 to 2.1.

I followed the instructions outlined here.

Try to remove <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion> or <NetStandardImplicitPackageVersion> section in the .csproj.

npx command not found

try :

sudo su

then

npm i npx 
or 
npi i -g npx

check your npx version by

npx -v

Angular - "has no exported member 'Observable'"

I replaced the original code with import { Observable, of } from 'rxjs', and the problem is solved.

enter image description here

enter image description here

AttributeError: Module Pip has no attribute 'main'

For me this issue occured when I was running python while within my site-packages folder. If I ran it anywhere else, it was no longer an issue.

Error after upgrading pip: cannot import name 'main'

I had this same error, but python -m pip was still working, so I fixed it with the nuclear option sudo python -m pip install --upgrade pip. It did it for me.

Error: Local workspace file ('angular.json') could not be found

Check out this link to migrate from Angular 5.2 to 6. https://update.angular.io/

Upgrading to version 8.9 worked for me. enter image description here

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)

Flutter.io Android License Status Unknown

I downgraded my Java version to 1.8 and its resolved, here is the link to download JDK8

Run the following command after installing JDK8

   flutter doctor --android-licenses

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

In Dart, if/else and switch are statements not expressions. They don't return a value so you can't pass them to constructor params. If you have a lot of conditional logic in your build method, then it is a good practice to try and simplify it. For example, you can move self-contained logic to methods, and use if/else statements to initialize local variables which you can later use.

Using a method and if/else

Widget _buildChild() {
  if (condition) {
    return ...
  }
  return ...
}

Widget build(BuildContext context) {
  return new Container(child: _buildChild());
}

Using an if/else

Widget build(BuildContext context) {
  Widget child;
  if (condition) {
    child = ...
  } else {
    child = ...
  }
  return new Container(child: child);
}

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

The answer to this question has changed as Jest has evolved. Current answer (March 2019):

  1. You can override the timeout of any individual test by adding a third parameter to the it. I.e., it('runs slow', () => {...}, 9999)

  2. You can change the default using jest.setTimeout. To do this:

    // Configuration
    "setupFilesAfterEnv": [  // NOT setupFiles
        "./src/jest/defaultTimeout.js"
    ],
    

    and

    // File: src/jest/defaultTimeout.js
    /* Global jest */
    jest.setTimeout(1000)
    
  3. Like others have noted, and not directly related to this, done is not necessary with the async/await approach.

Error occurred during initialization of boot layer FindException: Module not found

I faced same problem when I updated the Java version to 12.x. I was executing my project through Eclipse IDE. I am not sure whether this error is caused by compatibility issues.

However, I removed 12.x from my system and installed 8.x and my project started working fine.

How to run code after some delay in Flutter?

Just adding more description over the above answers

The Timer functionality works with below duration time also:

const Duration(
      {int days = 0,
      int hours = 0,
      int minutes = 0,
      int seconds = 0,
      int milliseconds = 0,
      int microseconds = 0})

Example:

  Timer(Duration(seconds: 3), () {
    print("print after every 3 seconds");
  });

Unable to compile simple Java 10 / Java 11 project with Maven

Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.

Checking for duplicate strings in JavaScript array

You can do this using a Set. You have to create a Set and put all the values in your Array, in that Set. Then, you check whether they have the same length or not. If not, you know there are duplicate values, because a Set can only have unique values. It is explained in the link below:

https://medium.com/dailyjs/how-to-remove-array-duplicates-in-es6-5daa8789641c

error: resource android:attr/fontVariationSettings not found

This is caused by an incompatibility with the android support library that changed to version 28. I solved the problem by forcing the build to use a lower support library. //like build gradle

configurations.all {
        resolutionStrategy {
                force 'com.android.support:support-v4:27.1.0'
    }
} 

My project built successfully immediately after I changed this. Hope this might help you too. I lost a day of development because of this!.

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

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

This can happens when one library is loaded into gradle several times. Most often through other connected libraries.

Remove a implementation this library in build.gradle

Then Build -> Clear project

and you can run the assembly)

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I have added in Application Class

@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

application.properties I have added

app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30

More details Configure a Custom DataSource

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

We can use ls and many other Linux commands in Windows cmd. Just follow these steps.

Steps:

1) Install Git in your computer - https://git-scm.com/downloads.

2) After installing Git, go to the folder in which Git is installed. Mostly it will be in C drive and then Program Files Folder.

3) In Program Files folder, you will find the folder named Git, find the bin folder which is inside usr folder in the Git folder.

In my case, the location for bin folder was - C:\Program Files\Git\usr\bin

4) Add this location (C:\Program Files\Git\usr\bin) in path variable, in system environment variables.

5) You are done. Restart cmd and try to run ls and other Linux commands.

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

All you need to do is to add USER to the owner of /local/lib

sudo chown -R $USER /usr/local/lib

EDIT :

To target precisely and only the node_modules folder, try using this command before using the previous one :

sudo chown -R $USER /usr/local/lib/node_modules

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

I'm using flow with vscode but had the same problem. I solved it with these steps:

  1. Install the extension Flow Language Support

  2. Disable the built-in TypeScript extension:

    1. Go to Extensions tab
    2. Search for @builtin TypeScript and JavaScript Language Features
    3. Click on Disable

Could not find a version that satisfies the requirement tensorflow

In case you are using Docker, make sure you have

FROM python:x.y.z

instead of

FROM python:x.y.z-alpine.

pull access denied repository does not exist or may require docker login

Please note that the error message from Docker is misleading.

$ docker build deploy/.
Sending build context to Docker daemon  5.632kB
Step 1/16 : FROM rhel7:latest
pull access denied for rhel7, repository does not exist or may require 'docker login'

It says that it may require 'docker login'. I struggled with this. I realized the image does not exist at https://hub.docker.com any more. I hope this helps someone.

You should not use <Link> outside a <Router>

Make it simple:

render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));

and don't forget: import { BrowserRouter } from "react-router-dom";

How do I deal with installing peer dependencies in Angular CLI?

Peer dependency warnings, more often than not, can be ignored. The only time you will want to take action is if the peer dependency is missing entirely, or if the version of a peer dependency is higher than the version you have installed.

Let's take this warning as an example:

npm WARN @angular/[email protected] requires a peer of @angular/[email protected] but none is installed. You must install peer dependencies yourself.

With Angular, you would like the versions you are using to be consistent across all packages. If there are any incompatible versions, change the versions in your package.json, and run npm install so they are all synced up. I tend to keep my versions for Angular at the latest version, but you will need to make sure your versions are consistent for whatever version of Angular you require (which may not be the most recent).

In a situation like this:

npm WARN [email protected] requires a peer of @angular/core@^2.4.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.

If you are working with a version of Angular that is higher than 4.0.0, then you will likely have no issues. Nothing to do about this one then. If you are using an Angular version under 2.4.0, then you need to bring your version up. Update the package.json, and run npm install, or run npm install for the specific version you need. Like this:

npm install @angular/[email protected] --save

You can leave out the --save if you are running npm 5.0.0 or higher, that version saves the package in the dependencies section of the package.json automatically.

In this situation:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

You are running Windows, and fsevent requires OSX. This warning can be ignored.

Hope this helps, and have fun learning Angular!

ReactJS: Maximum update depth exceeded error

In this case , this code

{<td><span onClick={this.toggle()}>Details</span></td>}

causes toggle function to call immediately and re render it again and again thus making infinite calls.

so passing only the reference to that toggle method will solve the problem.

so ,

{<td><span onClick={this.toggle}>Details</span></td>}

will be the solution code.

If you want to use the () , you should use an arrow function like this

{<td><span onClick={()=> this.toggle()}>Details</span></td>}

In case you want to pass parameters you should choose the last option and you can pass parameters like this

{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}

In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.

Not able to pip install pickle in python 3.6

Pickle is a module installed for both Python 2 and Python 3 by default. See the standard library for 3.6.4 and 2.7.

Also to prove what I am saying is correct try running this script:

import pickle
print(pickle.__doc__)

This will print out the Pickle documentation showing you all the functions (and a bit more) it provides.

Or you can start the integrated Python 3.6 Module Docs and check there.

As a rule of thumb: if you can import the module without an error being produced then it is installed

The reason for the No matching distribution found for pickle is because libraries for included packages are not available via pip because you already have them (I found this out yesterday when I tried to install an integrated package).

If it's running without errors but it doesn't work as expected I would think that you made a mistake somewhere (perhaps quickly check the functions you are using in the docs). Python is very informative with it's errors so we generally know if something is wrong.

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Once I used double slash while calling the API then I got the same error.

I had to call http://localhost:8080/getSomething but I did Like http://localhost:8080//getSomething. I resolved it by removing extra slash.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

Windows 10:

Android Studio -> File -> Other Settings -> Default Project Structure... -> JDK location:

copy string shown, such as:

C:\Program Files\Android\Android Studio\jre

In file locator directory window, right-click on "This PC" ->

Properties -> Advanced System Settings -> Environment Variables... -> System Variables

click on the New... button under System Variables, then type and paste respectively:

.......Variable name: JAVA_HOME

.......Variable value: C:\Program Files\Android\Android Studio\jre

and hit OK buttons to close out.

Some installations may require JRE_HOME to be set as well, the same way.

To check, open a NEW black console window, then type echo %JAVA_HOME% . You should get back the full path you typed into the system variable. Windows 10 seems to support spaces in the filename paths for system variables very well, and does not seem to need ~tilde eliding.

Issue in installing php7.2-mcrypt

I followed below steps to install mcrypt for PHP7.2 using PECL.

  1. Install PECL

apt-get install php-pecl

  1. Before installing MCRYPT you must install libmcrypt

apt-get install libmcrypt-dev libreadline-dev

  1. Install MCRYPT 1.0.1 using PECL

pecl install mcrypt-1.0.1

  1. After the successful installation

You should add "extension=mcrypt.so" to php.ini

Please comment below if you need any assistance. :-)

IMPORTANT !

According to php.net reference many (all) mcrypt functions have been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

How to check if pytorch is using the GPU?

Simply from command prompt or Linux environment run the following command.

python -c 'import torch; print(torch.cuda.is_available())'

The above should print True

python -c 'import torch; print(torch.rand(2,3).cuda())'

This one should print the following:

tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')

ERROR in Cannot find module 'node-sass'

Try sudo npm install [email protected] if your node version is 12.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

'mat-form-field' is not a known element - Angular 5 & Material2

@NgModule({
  declarations: [
    SearchComponent
  ],
  exports: [
    CommonModule,
    MatInputModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatDialogModule,
  ]
})
export class MaterialModule { }

Also, do not forget to import the MaterialModule in the imports array of AppModule.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I encountered a similar issue trying to use xlrd in jupyter notebook. I notice you are using a virtual environment and that was the key to my issue as well. I had xlrd installed in my venv, but I had not properly installed a kernel for that virtual environment in my notebook.

To get it to work, I created my virtual environment and activated it.

Then... pip install ipykernel

And then... ipython kernel install --user --name=myproject

Finally, start jupyter notebooks and when you create a new notebook, select the name you created (in this example, 'myproject')

Hope that helps.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I was running into this issue and it turned out that I needed to do this:

docker run ${image_name} bash -c "${command}"

Hope that helps someone who finds this error.

'react-scripts' is not recognized as an internal or external command

It is an error about react-scripts file missing in your node_modules/ directory at the time of installation.

Check your react-script dependency is avaliable or not in package.json.

If not available then add it manually via:

npm install react-scripts --save

installing urllib in Python3.6

yu have to install the correct version for your computer 32 or 63 bits thats all

db.collection is not a function when using MongoClient v3.0

It used to work with the older versions of MongoDb client ~ 2.2.33

Option 1: So you can either use the older version

npm uninstall mongodb --save

npm install [email protected] --save

Option 2: Keep using the newer version (3.0 and above) and modify the code a little bit.

let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
  if(err) throw err;
  let db = client.db('myTestingDb');
  db.collection('customers').find().toArray(function(err, result){
    if(err) throw err;
    console.log(result);
    client.close();
    });
 });

axios post request to send form data

https://www.npmjs.com/package/axios

Its Working

// "content-type": "application/x-www-form-urlencoded", // commit this

import axios from 'axios';

let requestData = {
      username : "[email protected]",
      password: "123456
    };
   
    const url = "Your Url Paste Here";

    let options = {
      method: "POST",
      headers: { 
        'Content-type': 'application/json; charset=UTF-8',

        Authorization: 'Bearer ' + "your token Paste Here",
      },
      data: JSON.stringify(requestData),
      url
    };
    axios(options)
      .then(response => {
        console.log("K_____ res :- ", response);
        console.log("K_____ res status:- ", response.status);
      })
      .catch(error => {
        console.log("K_____ error :- ", error);
      });

fetch request

fetch(url, {
    method: 'POST',
    body: JSON.stringify(requestPayload),           
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
        Authorization: 'Bearer ' + token,
    },
})
    // .then((response) => response.json()) .  // commit out this part if response body is empty
    .then((json) => {
        console.log("response :- ", json);
    }).catch((error)=>{
        console.log("Api call error ", error.message);
        alert(error.message);
});

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

No provider for Http StaticInjectorError

In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.

i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule

import { HttpModule } from '@angular/http';
import {   HttpClientModule } from '@angular/common/http';

ii) In @NgModule import sections add below lines:

HttpModule,
HttpClientModule,

So, in my case @NgModule, looks like this:

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [ ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule, 
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

That's it!

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

I tried all of the above and nothing worked for me.

Then I followed Gradle Settings > Build Execution, Deployment > Gradle > Android Studio and checked "Disable embedded Maven repository".

Did a build with this checked and the problem was solved.

NullInjectorError: No provider for AngularFirestore

Weird thing for me was that I had the provider:[], but the HTML tag that uses the provider was what was causing the error. I'm referring to the red box below: enter image description here

It turns out I had two classes in different components with the same "employee-list.component.ts" filename and so the project compiled fine, but the references were all messed up.

How to add CORS request in header in Angular 5

A POST with httpClient in Angular 6 was also doing an OPTIONS request:

Headers General:

Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData
Request Method:OPTIONS
Status Code:200 OK
Remote Address:127.0.0.1:443
Referrer Policy:no-referrer-when-downgrade

My Perl REST server implements the OPTIONS request with return code 200.

The next POST request Header:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:hp-probook
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36

Notice Access-Control-Request-Headers:content-type.

So, my backend perl script uses the following headers:


 -"Access-Control-Allow-Origin" => '*',
 -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS',
 -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',

With this setup the GET and POST worked for me!

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

How to import keras from tf.keras in Tensorflow?

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

In Keras (v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras (v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

Note: TensorFlow Version is 1.9

No provider for HttpClient

I was also facing similar issue by doing below changes, it worked for me

In app.modules.ts

import {HttpClientModule} from '@angular/common/http' 

and in corresponding service class

import { HttpClient } from '@angular/common/http'

constructor should look like as below

constructor(private http: HttpClient, private xyz: xyzService) {}

In test file

import { HttpClientTestingModule } from '@angular/common/http/testing'

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule]
  }));

Angular 5 Service to read local .json file

For Angular 7, I followed these steps to directly import json data:

In tsconfig.app.json:

add "resolveJsonModule": true in "compilerOptions"

In a service or component:

import * as exampleData from '../example.json';

And then

private example = exampleData;

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

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    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'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

Failed to run sdkmanager --list with Java 9

(WINDOWS)

If you have installed Android Studio already go to File >> Project Structure... >> SDK Location.

Go to that location + \cmdline-tools\latest\bin Copy the Path into Environment Variables

than it is OK to use the command line tool.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Set the buildToolsVersion '26.0.2' then change classpath 'com.android.tools.build:gradle:3.0.1'.

Make sure you set compileSdkVersion to 26 whiles targetSdkVersion is also set 26.

It is also appropriate to sent set compile 'com.android.support:appcompat-v7:26.0.2'.

Angular : Manual redirect to route

You should inject Router in your constructor like this;

constructor(private router: Router) { }

then you can do this anywhere you want;

this.router.navigate(['/product-list']);

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

Android Studio 3.0 Execution failed for task: unable to merge dex

This error happens when you add an external library which may not be compatible with your compileSdkVersion .

Be careful when you are adding an external library.

I spent 2 days on this problem and finally it got solved following these steps.

  • Make sure all your support libraries are same as compileSdkVersion of your build.gradle(Module:app) in my case it is 26. enter image description here

  • In your defaultConfig category type multiDexEnabled true. This is the important part. multiDexEnabled True image

  • Go to File | Settings | Build, Execution, Deployment | Instant Run and try to Enable/Disable Instant Run to hot swap... and click okay Enable Instant Run to Hot swap... Image

  • Sync Your project.

  • Lastly, Go to Build | click on Rebuild Project.

  • Note: Rebuild Project first cleans and then builds the project.

How to work with progress indicator in flutter?

1. Without plugin

    class IndiSampleState extends State<ProgHudPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('Demo'),
        ),
        body: Center(
          child: RaisedButton(
            color: Colors.blueAccent,
            child: Text('Login'),
            onPressed: () async {
              showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return Center(child: CircularProgressIndicator(),);
                  });
              await loginAction();
              Navigator.pop(context);
            },
          ),
        ));
  }

  Future<bool> loginAction() async {
    //replace the below line of code with your login request
    await new Future.delayed(const Duration(seconds: 2));
    return true;
  }
}

2. With plugin

check this plugin progress_hud

add the dependency in the pubspec.yaml file

dev_dependencies:
  progress_hud: 

import the package

import 'package:progress_hud/progress_hud.dart';

Sample code is given below to show and hide the indicator

class ProgHudPage extends StatefulWidget {
  @override
  _ProgHudPageState createState() => _ProgHudPageState();
}

class _ProgHudPageState extends State<ProgHudPage> {
  ProgressHUD _progressHUD;
  @override
  void initState() {
    _progressHUD = new ProgressHUD(
      backgroundColor: Colors.black12,
      color: Colors.white,
      containerColor: Colors.blue,
      borderRadius: 5.0,
      loading: false,
      text: 'Loading...',
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('ProgressHUD Demo'),
        ),
        body: new Stack(
          children: <Widget>[
            _progressHUD,
            new Positioned(
                child: RaisedButton(
                  color: Colors.blueAccent,
                  child: Text('Login'),
                  onPressed: () async{
                    _progressHUD.state.show();
                    await loginAction();
                    _progressHUD.state.dismiss();
                  },
                ),
                bottom: 30.0,
                right: 10.0)
          ],
        ));
  }

  Future<bool> loginAction()async{
    //replace the below line of code with your login request
    await new Future.delayed(const Duration(seconds: 2));
    return true;
  }
}

Angular 4 - Select default value in dropdown [Reactive Forms]

In your component -

Make sure to initialize the formControl name country with a value.

For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,

....
this.myForm = this._fb.group({
  country:[this.default]
})

and also try replacing [value] with [ngValue].

EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.

this.myForm.controls.country.controls.setValue(this.country) 

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

Add this in your module.ts,

declarations: [
  AppComponent,
  ConfirmComponent
]

if ConfirmComponent is in another module, you need to export it there thus you can use it outside, add:

exports: [ ConfirmComponent ]

---Update Angular 9 or Angular 8 with Ivy explicitly enabled---

Entry Components With Ivy are not required anymore and now are deprecated

---for Angular 9 and 8 with Ivy disabled---

In the case of a dynamically loaded component and in order for a ComponentFactory to be generated, the component must also be added to the module’s entryComponents:

declarations: [
  AppComponent,
  ConfirmComponent
],
entryComponents: [ConfirmComponent],

according to the definition of entryComponents

Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

Import data into Google Colaboratory

It has been solved, find details here and please use the function below: https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory/49467113#49467113

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):
        # author: yasser mustafa, 21 March 2018  
        # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

in my case the problem was into outdated "../bootstrap/cache/packages.php and services.php"

I have had to. drop those files and rerun composer install...

  Erroneous data format for unserializing 'Symfony\Component\Routing\CompiledRoute'


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

How to open local file on Jupyter?

Here's a possibile solution (in Python):

Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:

import os
notebook_path = os.path.abspath("Notebook.ipynb")

In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.

For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:

train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
    #....etc

The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.

Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

In my case, the problem I had was due to a dependency I was trying to import (BottomNavigationViewEx).

This dependency requires to be downloaded from jitpack.io and maven.google.com, and I was putting this config in buildscript section:

buildscript {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" } // this is incorrect
        maven { url "https://maven.google.com" } // this is incorrect
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    } 
}

which it was incorrect, I need to remove these two maven lines and include them in the right section, 'allprojects':

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

Hope it helps somebody as same for me.

How to know the git username and email saved during configuration?

List all variables set in the config file, along with their values.

git config --list

If you are new to git then use the following commands to set a user name and email address.

Set user name

git config --global user.name "your Name"

Set user email

git config --global user.email "[email protected]"

Check user name

git config user.name

Check user email

git config user.email

How to solve npm install throwing fsevents warning on non-MAC OS?

Instead of using --no-optional every single time, we can just add it to npm or yarn config.

For Yarn, there is a default no-optional config, so we can just edit that:

yarn config set ignore-optional true

For npm, there is no default config set, so we can create one:

npm config set ignore-optional true

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

I simply needed to update my project's dependencies and then restart the server.

How to read file with async/await properly?

You can use fs.promises available natively since Node v11.0.0

import fs from 'fs';

const readFile = async filePath => {
  try {
    const data = await fs.promises.readFile(filePath, 'utf8')
    return data
  }
  catch(err) {
    console.log(err)
  }
}

Angular: Cannot Get /

For me the issue was with @Component Selector path was pointing to wrong path. After changing it solved the issue.

@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html',
providers: [ToolbarService, GroupService, FilterService, PageService, ExcelExportService, PdfExportService]
})

React-Redux: Actions must be plain objects. Use custom middleware for async actions

I had same issue as I had missed adding composeEnhancers. Once this is setup then you can take a look into action creators. You get this error when this is not setup as well.

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(thunk))
);

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

You can also use renderRows() method.

@ViewChild(MatTable, {static: false}) table : MatTable // initialize

then this.table.renderRows();

for reference check this out -: https://www.freakyjolly.com/angular-7-8-edit-add-delete-rows-in-material-table-with-using-dialogs-inline-row-operation/

Is there a way to remove unused imports and declarations from Angular 2+?

If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:

...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.organizeImports": true
}
....

Hopefully this can be helpful!

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
  _x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. By making key value undefined: Alternate & a faster way:

_x000D_
_x000D_
let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
  };_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. With es6 spread Operator:

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
_x000D_
_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

How to use switch statement inside a React component?

I really liked the suggestion in https://stackoverflow.com/a/60313570/770134, so I adapted it to Typescript like so

import React, { FunctionComponent } from 'react'
import { Optional } from "typescript-optional";
const { ofNullable } = Optional

interface SwitchProps {
  test: string
  defaultComponent: JSX.Element
}

export const Switch: FunctionComponent<SwitchProps> = (props) => {
  return ofNullable(props.children)
    .map((children) => {
      return ofNullable((children as JSX.Element[]).find((child) => child.props['value'] === props.test))
        .orElse(props.defaultComponent)
    })
    .orElseThrow(() => new Error('Children are required for a switch component'))
}

const Foo = ({ value = "foo" }) => <div>foo</div>;
const Bar = ({ value = "bar" }) => <div>bar</div>;
const value = "foo";
const SwitchExample = <Switch test={value} defaultComponent={<div />}>
  <Foo />
  <Bar />
</Switch>;

Tensorflow import error: No module named 'tensorflow'

Since none of the above solve my issue, I will post my solution

WARNING: if you just installed TensorFlow using conda, you have to restart your command prompt!

Solution: restart terminal ENTIRELY and restart conda environment

Please add a @Pipe/@Directive/@Component annotation. Error

Not a solution to the concrete example above, but there may be many reasons why you get this error message. I got it when I accidentally added a shared module to the module declarations list and not to imports.

In app.module.ts:

import { SharedModule } from './modules/shared/shared.module';

@NgModule({
  declarations: [
     // Should not have been added here...
  ],
  imports: [
     SharedModule
  ],

cmake error 'the source does not appear to contain CMakeLists.txt'

Since you add .. after cmake, it will jump up and up (just like cd ..) in the directory. But if you want to run cmake under the same folder with CMakeLists.txt, please use . instead of ...

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

How to rename a component in Angular CLI?

While the OP asks for a CLI command, some of the answers focus on the IDEs. In this answer I just confirm, that the current WebStorm/IntelliJ does allow renaming the component. All that needs to be done is attempting to rename the class in the .ts file. You will be presented with:

enter image description here

and the rename will be performed in all relevant places.

Angular HttpClient "Http failure during parsing"

Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);

Becuase if you turn it to text but backend asks for json, it will return an error...

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

Vuejs: Event on route change

Another solution for typescript user:

import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For TFS 2013:

Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.

Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes

In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:

  • Ignore this item
  • Ignore by extension
  • Ignore by file name
  • Ignore by ffolder (yes ffolder, TFS 2013 Update 4/Visual Studio 2013 Premium Update 4)

Don't forget to Check In the changed .tfignore-File.

For VS 2015/2017:

The same procedure: In the "Excluded Changes Tab" in TeamExplorer\Pending Changes click on Detected: xxx add(s)

The Excluded Changes Tab in TeamExplorer\Pending Changes

The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)

What is the difference between user and kernel modes in operating systems?

What

Basically the difference between kernel and user modes is not OS dependent and is achieved only by restricting some instructions to be run only in kernel mode by means of hardware design. All other purposes like memory protection can be done only by that restriction.

How

It means that the processor lives in either the kernel mode or in the user mode. Using some mechanisms the architecture can guarantee that whenever it is switched to the kernel mode the OS code is fetched to be run.

Why

Having this hardware infrastructure these could be achieved in common OSes:

  • Protecting user programs from accessing whole the memory, to not let programs overwrite the OS for example,
  • preventing user programs from performing sensitive instructions such as those that change CPU memory pointer bounds, to not let programs break their memory bounds for example.

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

try{

     let vari = obj.propTest; // obj may be don't have propTest property

        ...
} catch(NullException){
    // do something here
}

I think using try catch will avoid any error of null check, also in Angular or JavaScript Just catching null exception and process in it.

How to plot an array in python?

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

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

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

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

import numpy as np
import matplotlib.pyplot as plt

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

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

Jupyter matplotlib plot

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

How to debug Ruby scripts

I just discovered this gem ( turns Pry into a debugger for MRI Ruby 2.0+ )

https://github.com/deivid-rodriguez/pry-byebug

Install with:

gem install pry-byebug

then use exactly like pry, mark the line you want to break at:

require 'pry'; binding.pry

Unlike vanilla pry however, this gem has some key GDB-like navigation commands such as next, step and break:

break SomeClass#run            # Break at the start of `SomeClass#run`.
break Foo#bar if baz?          # Break at `Foo#bar` only if `baz?`.
break app/models/user.rb:15    # Break at line 15 in user.rb.
break 14                       # Break at line 14 in the current file.

Make EditText ReadOnly

If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.

code:

myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);

xml:

<TextView
    android:textIsSelectable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"     
    ...
/>
<!--android:selectAllOnFocus="true"-->


The documentation of setTextIsSelectable says:

When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...

However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.

How can I stage and commit all files, including newly added files, using a single command?

I have in my config two aliases:

alias.foo=commit -a -m 'none'
alias.coa=commit -a -m

if I am too lazy I just commit all changes with

git foo

and just to do a quick commit

git coa "my changes are..."

coa stands for "commit all"

Unable to make the session state request to the session state server

One of my clients was facing the same issue. Following steps are taken to fix this.

 (1) Open Run. 

 (2) Type Services.msc

 (3) Select ASP.NET State Service

 (4) Right Click and Start it.

Setting up and using Meld as your git difftool and mergetool

I prefer to setup meld as a separate command, like so:

git config --global alias.meld '!git difftool -t meld --dir-diff'

This makes it similar to the git-meld.pl script here: https://github.com/wmanley/git-meld

You can then just run

git meld

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In my case, this error happened because my HTML had a trailing linebreak.

var myHtml = '<p>\
    This should work.\
    But does not.\
</p>\
';

jQuery('.something').append(myHtml); // this causes the error

To avoid the error, you just need to trim the HTML.

jQuery('.something').append(jQuery.trim(myHtml)); // this works

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

Android Support Design TabLayout: Gravity Center and Mode Scrollable

This is the only code that worked for me:

public static void adjustTabLayoutBounds(final TabLayout tabLayout,
                                         final DisplayMetrics displayMetrics){

    final ViewTreeObserver vto = tabLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            tabLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            int totalTabPaddingPlusWidth = 0;
            for(int i=0; i < tabLayout.getTabCount(); i++){

                final LinearLayout tabView = ((LinearLayout)((LinearLayout) tabLayout.getChildAt(0)).getChildAt(i));
                totalTabPaddingPlusWidth += (tabView.getMeasuredWidth() + tabView.getPaddingLeft() + tabView.getPaddingRight());
            }

            if (totalTabPaddingPlusWidth <= displayMetrics.widthPixels){

                tabLayout.setTabMode(TabLayout.MODE_FIXED);
                tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

            }else{
                tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
            }

            tabLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }
    });
}

The DisplayMetrics can be retrieved using this:

public DisplayMetrics getDisplayMetrics() {

    final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    final Display display = wm.getDefaultDisplay();
    final DisplayMetrics displayMetrics = new DisplayMetrics();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        display.getMetrics(displayMetrics);

    }else{
        display.getRealMetrics(displayMetrics);
    }

    return displayMetrics;
}

And your TabLayout XML should look like this (don't forget to set tabMaxWidth to 0):

<android.support.design.widget.TabLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tab_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:tabMaxWidth="0dp"/>

Deleting all pending tasks in celery / rabbitmq

celery 4+ celery purge command to purge all configured task queues

celery -A *APPNAME* purge

programmatically:

from proj.celery import app
app.control.purge()

all pending task will be purged. Reference: celerydoc

centos: Another MySQL daemon already running with the same unix socket

It may sometime arises when MySQL service does not shut down properly during the OS reboot. The /var/lib/mysql/mysql.sock has been left. This prevents 'mysqld' from starting up.

These steps may help:

1: service mysqld start killall -9 mysqld_safe mysqld service mysqld start

2: rm /var/lib/mysql/mysql.sock service mysqld start

Regarding Java switch statements - using return and omitting breaks in each case

If you're going to have a method that just runs the switch and then returns some value, then sure this way works. But if you want a switch with other stuff in a method then you can't use return or the rest of the code inside the method will not execute. Notice in the tutorial how it has a print after the code? Yours would not be able to do this.

Angular JS update input field after change

Create a directive and put a watch on it.

app.directive("myApp", function(){
link:function(scope){

    function:getTotal(){
    ..do your maths here

    }
    scope.$watch('one', getTotals());
    scope.$watch('two', getTotals());
   }

})

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

There is one rather sneaky trick not mentioned here so far. We assume that you have no extra way to store data, but that is not strictly true.

One way around your problem is to do the following horrible thing, which should not be attempted by anyone under any circumstances: Use the network traffic to store data. And no, I don't mean NAS.

You can sort the numbers with only a few bytes of RAM in the following way:

  • First take 2 variables: COUNTER and VALUE.
  • First set all registers to 0;
  • Every time you receive an integer I, increment COUNTER and set VALUE to max(VALUE, I);
  • Then send an ICMP echo request packet with data set to I to the router. Erase I and repeat.
  • Every time you receive the returned ICMP packet, you simply extract the integer and send it back out again in another echo request. This produces a huge number of ICMP requests scuttling backward and forward containing the integers.

Once COUNTER reaches 1000000, you have all of the values stored in the incessant stream of ICMP requests, and VALUE now contains the maximum integer. Pick some threshold T >> 1000000. Set COUNTER to zero. Every time you receive an ICMP packet, increment COUNTER and send the contained integer I back out in another echo request, unless I=VALUE, in which case transmit it to the destination for the sorted integers. Once COUNTER=T, decrement VALUE by 1, reset COUNTER to zero and repeat. Once VALUE reaches zero you should have transmitted all integers in order from largest to smallest to the destination, and have only used about 47 bits of RAM for the two persistent variables (and whatever small amount you need for the temporary values).

I know this is horrible, and I know there can be all sorts of practical issues, but I thought it might give some of you a laugh or at least horrify you.

How do I remove blank pages coming between two chapters in Appendix?

I tried Noah's suggestion which leads to the best solution up to now.

Just insert \let\cleardoublepage\clearpage before all the parts with the blank pages Especially when you use \documentclass[12pt,a4paper]{book}

frederic snyers's advice \documentclass[oneside]{book} is also very good and solves the problem, but if we just want to use the book.cls or article.cls, the one would make a big difference presenting your particles.

Hence, Big support to \let\cleardoublepage\clearpage for the people who will ask the same question in the future.

How can I read comma separated values from a text file in Java?

Use BigDecimal, not double

The Answer by adatapost is right about using String::split but wrong about using double to represent your longitude-latitude values. The float/Float and double/Double types use floating-point technology which trades away accuracy for speed of execution.

Instead use BigDecimal to correctly represent your lat-long values.

Use Apache Commons CSV library

Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.

Example app

Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split for the writing. And the app uses BigDecimal objects to represent your lat-long values.

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class LatLong
{
    //----------|  Write  |-----------------------------
    public void write ( final Path path )
    {
        List < String > inputs =
                List.of(
                        "28.515046280572285,77.38258838653564" ,
                        "28.51430151808072,77.38336086273193" ,
                        "28.513566177802456,77.38413333892822" ,
                        "28.512830832397192,77.38490581512451" ,
                        "28.51208605426073,77.3856782913208" ,
                        "28.511341270865113,77.38645076751709" );

        // Use try-with-resources syntax to auto-close the `CSVPrinter`.
        try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
        {
            for ( String input : inputs )
            {
                String[] fields = input.split( "," );
                printer.printRecord( fields[ 0 ] , fields[ 1 ] );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Read  |-----------------------------
    public void read ( Path path )
    {
        // TODO: Add a check for valid file existing.

        try
        {
            // Read CSV file.
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            for ( CSVRecord record : records )
            {
                BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
                BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
                System.out.println( "lat: " + latitude + " | long: " + longitude );
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    //----------|  Main  |-----------------------------
    public static void main ( String[] args )
    {
        LatLong app = new LatLong();

        // Write
        Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.write( pathOutput );
        System.out.println( "Writing file: " + pathOutput );

        // Read
        Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
        app.read( pathInput );

        System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
    }

}

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

How do I get the current location of an iframe?

You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.

http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx

Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.

how to get all markers on google-maps-v3

For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.

For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.

Best approach to real time http streaming to HTML5 video client

EDIT 3: As of IOS 10, HLS will support fragmented mp4 files. The answer now, is to create fragmented mp4 assets, with a DASH and HLS manifest. > Pretend flash, iOS9 and below and IE 10 and below don't exist.

Everything below this line is out of date. Keeping it here for posterity.


EDIT 2: As people in the comments are pointing out, things change. Almost all browsers will support AVC/AAC codecs. iOS still requires HLS. But via adaptors like hls.js you can play HLS in MSE. The new answer is HLS+hls.js if you need iOS. or just Fragmented MP4 (i.e. DASH) if you don't

There are many reasons why video and, specifically, live video is very difficult. (Please note that the original question specified that HTML5 video is a requirement, but the asker stated Flash is possible in the comments. So immediately, this question is misleading)

First I will restate: THERE IS NO OFFICIAL SUPPORT FOR LIVE STREAMING OVER HTML5. There are hacks, but your mileage may vary.

EDIT: since I wrote this answer Media Source Extensions have matured, and are now very close to becoming a viable option. They are supported on most major browsers. IOS continues to be a hold out.

Next, you need to understand that Video on demand (VOD) and live video are very different. Yes, they are both video, but the problems are different, hence the formats are different. For example, if the clock in your computer runs 1% faster than it should, you will not notice on a VOD. With live video, you will be trying to play video before it happens. If you want to join a a live video stream in progress, you need the data necessary to initialize the decoder, so it must be repeated in the stream, or sent out of band. With VOD, you can read the beginning of the file them seek to whatever point you wish.

Now let's dig in a bit.

Platforms:

  • iOS
  • PC
  • Mac
  • Android

Codecs:

  • vp8/9
  • h.264
  • thora (vp3)

Common Delivery methods for live video in browsers:

  • DASH (HTTP)
  • HLS (HTTP)
  • flash (RTMP)
  • flash (HDS)

Common Delivery methods for VOD in browsers:

  • DASH (HTTP Streaming)
  • HLS (HTTP Streaming)
  • flash (RTMP)
  • flash (HTTP Streaming)
  • MP4 (HTTP pseudo streaming)
  • I'm not going to talk about MKV and OOG because I do not know them very well.

html5 video tag:

  • MP4
  • webm
  • ogg

Lets look at which browsers support what formats

Safari:

  • HLS (iOS and mac only)
  • h.264
  • MP4

Firefox

  • DASH (via MSE but no h.264)
  • h.264 via Flash only!
  • VP9
  • MP4
  • OGG
  • Webm

IE

  • Flash
  • DASH (via MSE IE 11+ only)
  • h.264
  • MP4

Chrome

  • Flash
  • DASH (via MSE)
  • h.264
  • VP9
  • MP4
  • webm
  • ogg

MP4 cannot be used for live video (NOTE: DASH is a superset of MP4, so don't get confused with that). MP4 is broken into two pieces: moov and mdat. mdat contains the raw audio video data. But it is not indexed, so without the moov, it is useless. The moov contains an index of all data in the mdat. But due to its format, it can not be 'flattened' until the timestamps and size of EVERY frame is known. It may be possible to construct an moov that 'fibs' the frame sizes, but is is very wasteful bandwidth wise.

So if you want to deliver everywhere, we need to find the least common denominator. You will see there is no LCD here without resorting to flash example:

  • iOS only supports h.264 video. and it only supports HLS for live.
  • Firefox does not support h.264 at all, unless you use flash
  • Flash does not work in iOS

The closest thing to an LCD is using HLS to get your iOS users, and flash for everyone else. My personal favorite is to encode HLS, then use flash to play HLS for everyone else. You can play HLS in flash via JW player 6, (or write your own HLS to FLV in AS3 like I did)

Soon, the most common way to do this will be HLS on iOS/Mac and DASH via MSE everywhere else (This is what Netflix will be doing soon). But we are still waiting for everyone to upgrade their browsers. You will also likely need a separate DASH/VP9 for Firefox (I know about open264; it sucks. It can't do video in main or high profile. So it is currently useless).

Has an event handler already been added?

This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.

public class MyClass
{
  event Action MyEvent;
}

...

MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;

...

Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example

Console.WriteLine(handlers[0].Method.Name);//prints the name of the method

You can examine various properties on the Method property of the delegate to see if a specific function has been added.

If you are looking to see if there is just one attached, you can just test for null.

How to get a string between two characters?

The least generic way I found to do this with Regex and Pattern / Matcher classes:

String text = "test string (67)";

String START = "\\(";  // A literal "(" character in regex
String END   = "\\)";  // A literal ")" character in regex

// Captures the word(s) between the above two character(s)
String pattern = START + "(\w+)" + END;

Pattern pattern = Pattern.compile(pattern);
Matcher matcher = pattern.matcher(text);

while(matcher.find()) {
    System.out.println(matcher.group()
        .replace(START, "").replace(END, ""));
}

This may help for more complex regex problems where you want to get the text between two set of characters.

Set the value of an input field

If you are using multiple forms, you can use:

<form name='myForm'>
    <input type='text' name='name' value=''>
</form>

<script type="text/javascript"> 
    document.forms['myForm']['name'].value = "New value";
</script>

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I think you will understand it through these examples below.

Source code structure:

/src/main/webapp/subdir/sample.jsp
/src/main/webapp/sample.jsp

Context is: TestApp
So the entry point: http://yourhostname-and-port/TestApp


Forward to RELATIVE path:

Using servletRequest.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> \subdir\sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character
http://yourhostname-and-port/TestApp/fwdServlet ==> java.lang.IllegalArgumentException: Path sample.jsp does not start with a "/" character


Forward to ABSOLUTE path:

Using servletRequest.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet  ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Using servletContext.getRequestDispatcher("/sample.jsp"):

http://yourhostname-and-port/TestApp/subdir/fwdServlet ==> /sample.jsp
http://yourhostname-and-port/TestApp/fwdServlet ==> /sample.jsp

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

if you have Firebase included also, make them of same version as the error says.

PHPMailer: SMTP Error: Could not connect to SMTP host

$mail->SMTPDebug = 2; // to see exactly what's the issue

In my case this helped:

$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;

what does -zxvf mean in tar -zxvf <filename>?

Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference under the info tar command.

x means --extract. v means --verbose. f means --file. z means --gzip. You can combine one-letter arguments together, and f takes an argument, the filename. There is something you have to watch out for:

Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).


This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:

 tar cfz archive.tar.gz file
 tar -cfz archive.tar.gz file

are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.

Python non-greedy regexes

As the others have said using the ? modifier on the * quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Convert month name to month number in SQL Server

You can create a function and then refer to it in the select statement. The function may look similar to this:

if OBJECT_ID('fn_month_name_to_number', 'IF') is not null
drop function fn_month_name_to_number
go
create function fn_month_name_to_number (@monthname varchar(25))
returns int as
begin
declare @monthno as int;
select @monthno =
case @monthname
when 'January' then 1
when 'February' then 2
when 'March' then 3
when 'April' then 4
when 'May' then 5
when 'June' then 6
when 'July' then 7
when 'August' then 8
when 'September' then 9
when 'October' then 10
when 'November' then 11
when 'December' then 12
end
return @monthno
end

Then you can query it.

select fn_month_name_to_number ('February') as month_no

This query will return 2 as month number. You can pass values from a column as parameters to the function.

select fn_month_name_to_number (*columnname*) as month_no from *tablename*

Have a good day!

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

How do you list the primary key of a SQL Server table?

For a comma separated list of primary key columns for a given TableName and Schema:

Select distinct SUBSTRING ( stuff(( select distinct ',' + [COLUMN_NAME] 
                                    from INFORMATION_SCHEMA.KEY_COLUMN_USAGE  
                                    where OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1  
                                    AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'  
                                    order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,0,'' ) 
                            ,2,9999) 

Getting all file names from a folder using C#

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx

The System.IO namespace has loads of methods to help you with file operations. The

Directory.GetFiles() 

method returns an array of strings which represent the files in the target directory.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

It's a bit of a guess but could the quotes around happy be the problem? There have been some problems in the past where Android would either add or not recognize quotes around an SSID. Try setting up the hosted network connection again, but without the quotes that we see in the output for netsh wlan show hostednetwork.

What is the correct syntax of ng-include?

    <ng-include src="'views/sidepanel.html'"></ng-include>

OR

    <div ng-include="'views/sidepanel.html'"></div>

OR

    <div ng-include src="'views/sidepanel.html'"></div>

Points To Remember:

--> No spaces in src

--> Remember to use single quotation in double quotation for src

CSS force image resize and keep aspect ratio

To force image that fit in a exact size, you don't need to write too many codes. It's so simple

_x000D_
_x000D_
img{_x000D_
    width: 200px;_x000D_
    height: auto;_x000D_
    object-fit: contain; /* Fit logo in the image size */_x000D_
        -o-object-fit: contain; /* Fit logo fro opera browser */_x000D_
    object-position: top; /* Set logo position */_x000D_
        -o-object-position: top; /* Logo position for opera browser */_x000D_
    }
_x000D_
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">
_x000D_
_x000D_
_x000D_

Why use Optional.of over Optional.ofNullable?

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

Where are the Android icon drawables within the SDK?

In android.R.drawable, read more here : http://docs.since2006.com/android/2.1-drawables.php


Simple resource usage :

android:icon="@android:drawable/ic_menu_save"

Simple Java usage :

myMenuItem.setIcon(android.R.drawable.ic_menu_save);

java- reset list iterator to first element of the list

This is an alternative solution, but one could argue it doesn't add enough value to make it worth it:

import com.google.common.collect.Iterables;
...
Iterator<String> iter = Iterables.cycle(list).iterator();
if(iter.hasNext()) {
    str = iter.next();
}

Calling hasNext() will reset the iterator cursor to the beginning if it's a the end.

jquery beforeunload when closing (not leaving) the page?

Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?

Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.

var link_was_clicked = false;
document.addEventListener("click", function(e) {
   if (e.target.nodeName.toLowerCase() === 'a') {
      link_was_clicked = true;
   }
}, true);

window.onbeforeunload = function(e) {
    if(link_was_clicked) {
        return;
    }
    return confirm('Are you sure?');
}

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Write a file in UTF-8 using FileWriter (Java)?

use OutputStream instead of FileWriter to set encoding type

// file is your File object where you want to write you data 
OutputStream outputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(json); // json is your data 
outputStreamWriter.flush();
outputStreamWriter.close();

What does "request for member '*******' in something not a structure or union" mean?

I have enumerated possibly all cases where this error may occur in code and its comments below. Please add to it, if you come across more cases.

#include<stdio.h>
#include<malloc.h>

typedef struct AStruct TypedefedStruct;

struct AStruct
{
    int member;
};

void main()
{
    /*  Case 1
        ============================================================================
        Use (->) operator to access structure member with structure pointer, instead
        of dot (.) operator. 
    */
    struct AStruct *aStructObjPtr = (struct AStruct *)malloc(sizeof(struct AStruct));
    //aStructObjPtr.member = 1;      //Error: request for member ‘member’ in something not 
                                      //a structure or union. 
                                      //It should be as below.
    aStructObjPtr->member = 1;
    printf("%d",aStructObjPtr->member); //1


    /*  Case 2
        ============================================================================
        We can use dot (.) operator with struct variable to access its members, but 
        not with with struct pointer. But we have to ensure we dont forget to wrap 
        pointer variable inside brackets.
    */
    //*aStructObjPtr.member = 2;     //Error, should be as below.
    (*aStructObjPtr).member = 2;
    printf("%d",(*aStructObjPtr).member); //2


    /* Case 3
       =============================================================================
       Use (->) operator to access structure member with typedefed structure pointer, 
       instead of dot (.) operator. 
    */
    TypedefedStruct *typedefStructObjPtr = (TypedefedStruct *)malloc(sizeof(TypedefedStruct));
    //typedefStructObjPtr.member=3;  //Error, should be as below.
    typedefStructObjPtr->member=3;
    printf("%d",typedefStructObjPtr->member);  //3


    /*  Case 4
        ============================================================================
        We can use dot (.) operator with struct variable to access its members, but 
        not with with struct pointer. But we have to ensure we dont forget to wrap 
        pointer variable inside brackets.
    */
    //*typedefStructObjPtr.member = 4;  //Error, should be as below.    
    (*typedefStructObjPtr).member=4;
    printf("%d",(*typedefStructObjPtr).member);  //4


    /* Case 5
       ============================================================================
       We have to be extra carefull when dealing with pointer to pointers to 
       ensure that we follow all above rules.
       We need to be double carefull while putting brackets around pointers.
    */

    //5.1. Access via struct_ptrptr and  ->
    struct AStruct **aStructObjPtrPtr = &aStructObjPtr;
    //*aStructObjPtrPtr->member = 5;  //Error, should be as below.
    (*aStructObjPtrPtr)->member = 5;
    printf("%d",(*aStructObjPtrPtr)->member); //5

    //5.2. Access via struct_ptrptr and .
    //**aStructObjPtrPtr.member = 6;  //Error, should be as below.
    (**aStructObjPtrPtr).member = 6;
    printf("%d",(**aStructObjPtrPtr).member); //6

    //5.3. Access via typedefed_strct_ptrptr and ->
    TypedefedStruct **typedefStructObjPtrPtr = &typedefStructObjPtr;
    //*typedefStructObjPtrPtr->member = 7;  //Error, should be as below.
    (*typedefStructObjPtrPtr)->member = 7;
    printf("%d",(*typedefStructObjPtrPtr)->member); //7

    //5.4. Access via typedefed_strct_ptrptr and .
    //**typedefStructObjPtrPtr->member = 8;  //Error, should be as below.
    (**typedefStructObjPtrPtr).member = 8;
    printf("%d",(**typedefStructObjPtrPtr).member); //8

    //5.5. All cases 5.1 to 5.4 will fail if you include incorrect number of *
    //     Below are examples of such usage of incorrect number *, correspnding
    //     to int values assigned to them

    //(aStructObjPtrPtr)->member = 5; //Error
    //(*aStructObjPtrPtr).member = 6; //Error 
    //(typedefStructObjPtrPtr)->member = 7; //Error 
    //(*typedefStructObjPtrPtr).member = 8; //Error
}

The underlying ideas are straight:

  • Use . with structure variable. (Cases 2 and 4)
  • Use -> with pointer to structure. (Cases 1 and 3)
  • If you reach structure variable or pointer to structure variable by following pointer, then wrap the pointer inside bracket: (*ptr). and (*ptr)-> vs *ptr. and *ptr-> (All cases except case 1)
  • If you are reaching by following pointers, ensure you have correctly reached pointer to struct or struct whichever is desired. (Case 5, especially 5.5)

Inline SVG in CSS

For people who are still struggling, I managed to get this working on all modern browsers IE11 and up.

base64 was no option for me because I wanted to use SASS to generate SVG icons based on any given color. For example: @include svg_icon(heart, #FF0000); This way I can create a certain icon in any color, and only have to embed the SVG shape once in the CSS. (with base64 you'd have to embed the SVG in every single color you want to use)

There are three things you need be aware of:

  1. URL ENCODE YOUR SVG As others have suggested, you need to URL encode your entire SVG string for it to work in IE11. In my case, I left out the color values in fields such as fill="#00FF00" and stroke="#FF0000" and replaced them with a SASS variable fill="#{$color-rgb}" so these can be replaced with the color I want. You can use any online converter to URL encode the rest of the string. You'll end up with an SVG string like this:

    %3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%2041.012%2010.535%2079.541%2028.973%20113.104L3.825%20464.586c345%2012.797%2041.813%2012.797%2015.467%200%2029.872-4.721%2041.813-12.797v158.184z%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E


  1. OMIT THE UTF8 CHARSET IN THE DATA URL When creating your data URL, you need to leave out the charset for it to work in IE11.

    NOT background-image: url( data:image/svg+xml;utf-8,%3Csvg%2....)
    BUT background-image: url( data:image/svg+xml,%3Csvg%2....)


  1. USE RGB() INSTEAD OF HEX colors Firefox does not like # in the SVG code. So you need to replace your color hex values with RGB ones.

    NOT fill="#FF0000"
    BUT fill="rgb(255,0,0)"

In my case I use SASS to convert a given hex to a valid rgb value. As pointed out in the comments, it's best to URL encode your RGB string as well (so comma becomes %2C)

@mixin svg_icon($id, $color) {
   $color-rgb: "rgb(" + red($color) + "%2C" + green($color) + "%2C" + blue($color) + ")";
   @if $id == heart {
      background-image: url('data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20494.572%20494.572%27%20width%3D%27512%27%20height%3D%27512%27%3E%0A%20%20%3Cpath%20d%3D%27M257.063%200C127.136%200%2021.808%20105.33%2021.808%20235.266c0%204%27%20fill%3D%27#{$color-rgb}%27%2F%3E%3C%2Fsvg%3E');
   }
}

I realize this might not be the best solution for very complex SVG's (inline SVG never is in that case), but for flat icons with only a couple of colors this really works great.

I was able to leave out an entire sprite bitmap and replace it with inline SVG in my CSS, which turned out to only be around 25kb after compression. So it's a great way to limit the amount of requests your site has to do, without bloating your CSS file.

Android and Facebook share intent

    public void invokeShare(Activity activity, String quote, String credit) {
    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject));
    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text");    
    shareIntent.putExtra("com.facebook.platform.extra.APPLICATION_ID", activity.getString(R.string.app_id));                        
    activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title)));
}

XSS prevention in JSP/Servlet web application

My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.

How to read data of an Excel file using C#?

First of all, it's important to know what you mean by "open an Excel file for reading and copy it to clipboard..."

This is very important because there are many ways you could do that depending just on what you intend to do. Let me explain:

  1. If you want to read a set of data and copy that in the clipboard and you know the data format (e.g. column names), I suggest you use an OleDbConnection to open the file, this way you can treat the xls file content as a Database Table, so you can read data with SQL instruction and treat the data as you want.

  2. If you want to do operations on the data with the Excel object model then open it in the way you began.

  3. Some time it's possible to treat an xls file as a kind of csv file, there are tools like File Helpers which permit you to treat and open an xls file in a simple way by mapping a structure on an arbitrary object.

Another important point is in which Excel version the file is.

I have, unfortunately I say, a strong experience working with Office automation in all ways, even if bounded in concepts like Application Automation, Data Management and Plugins, and generally I suggest only as the last resort, to using Excel automation or Office automation to read data; just if there aren't better ways to accomplish that task.

Working with automation could be heavy in performance, in terms of resource cost, could involve in other issues related for example to security and more, and last but not at least, working with COM interop it's not so "free".. So my suggestion is think and analyze the situation within your needs and then take the better way.

How to get current user who's accessing an ASP.NET application?

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

C++: Converting Hexadecimal to Decimal

#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    int x, y;
    std::stringstream stream;

    std::cin >> x;
    stream << x;
    stream >> std::hex >> y;
    std::cout << y;

    return 0;
}

How to add a named sheet at the end of all Excel sheets?

This is a quick and simple add of a named tab to the current worksheet:

Sheets.Add.Name = "Tempo"

HTML5 event handling(onfocus and onfocusout) using angular 2

I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

Interesting to note, all sources emphasize that @Column(nullable=false) is used only for DDL generation.

However, even if there is no @NotNull annotation, and hibernate.check_nullability option is set to true, Hibernate will perform validation of entities to be persisted.

It will throw PropertyValueException saying that "not-null property references a null or transient value", if nullable=false attributes do not have values, even if such restrictions are not implemented in the database layer.

More information about hibernate.check_nullability option is available here: http://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/Hibernate_User_Guide.html#configurations-mapping.

Showing which files have changed between two revisions

One more option, using meld in this case:

git difftool -d master otherbranch

This allows not only to see the differences between files, but also provides a easy way to point and click into a specific file.

Restore a deleted file in the Visual Studio Code Recycle Bin

It uses the normal trash bin of your system. So you can grab it our of there.

In Windows you find it in the explorer, in Linux it is as well in Konquerer / Nemo / ...

How to read HDF5 files in Python

What you need to do is create a dataset. If you take a look at the quickstart guide, it shows you that you need to use the file object in order to create a dataset. So, f.create_dataset and then you can read the data. This is explained in the docs.

How to display the string html contents into webbrowser control?

Old question, but here's my go-to for this operation.

If browser.Document IsNot Nothing Then
    browser.Document.OpenNew(True)
    browser.Document.Write(My.Resources.htmlTemplate)
Else
    browser.DocumentText = My.Resources.htmlTemplate
End If

And be sure that any browser.Navigating event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser navigating.

Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating

    Try
        Me.Cursor = Cursors.WaitCursor

        Select Case e.Url.Scheme

            Case Constants.App_Url_Scheme

                Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)

                Select Case e.Url.Host

                    Case Constants.Navigation.URLs.ToggleExpander.Host

                        Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)

                        :
                        :
                        <other operations here>
                        :
                        :

                End Select

            Case Else
                e.Cancel = (e.Url.ToString() <> "about:blank")

        End Select

    Catch ex As Exception
        ExceptionBox.Show(ex, "Operation failed.")
    Finally
        Me.Cursor = Cursors.Default
    End Try

End Sub

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

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

The easiest way i found to solve that problem was to select a label and then send:

label.sendKeys(Keys.PAGE_DOWN);

Hope it works!

How to to send mail using gmail in Laravel?

The problem for me is that for some reason the username/password came NULL from mail config. To check that before sending a email check with the follow code:

dd(Config::get('mail'));

If your username/password came nulled just set with:

Config::set('mail.username', 'yourusername');
Config::set('mail.password', 'yourpassword');

regex match any single character (one character only)

Match any single character

  • Use the dot . character as a wildcard to match any single character.

Example regex: a.c

abc   // match
a c   // match
azc   // match
ac    // no match
abbc  // no match

Match any specific character in a set

  • Use square brackets [] to match any characters in a set.
  • Use \w to match any single alphanumeric character: 0-9, a-z, A-Z, and _ (underscore).
  • Use \d to match any single digit.
  • Use \s to match any single whitespace character.

Example 1 regex: a[bcd]c

abc   // match
acc   // match
adc   // match
ac    // no match
abbc  // no match

Example 2 regex: a[0-7]c

a0c   // match
a3c   // match
a7c   // match
a8c   // no match
ac    // no match
a55c  // no match

Match any character except ...

Use the hat in square brackets [^] to match any single character except for any of the characters that come after the hat ^.

Example regex: a[^abc]c

aac   // no match
abc   // no match
acc   // no match
a c   // match
azc   // match
ac    // no match
azzc  // no match

(Don't confuse the ^ here in [^] with its other usage as the start of line character: ^ = line start, $ = line end.)

Match any character optionally

Use the optional character ? after any character to specify zero or one occurrence of that character. Thus, you would use .? to match any single character optionally.

Example regex: a.?c

abc   // match
a c   // match
azc   // match
ac    // match
abbc  // no match

See also

Creating a LinkedList class from scratch

class Node
{
  int data;
     Node link;

     public Node()
     {
         data=0;
         link=null;
        }

     Node ptr,start,temp;

    void create()throws  IOException
     {
         int n;
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("Enter first data");
         this.data=Integer.parseInt(br.readLine());
         ptr=this;
         start=ptr;
         char ins ='y';
         do
         {
             System.out.println("Wanna Insert another node???");
             ins=(char)br.read();
             br.read();
             if(ins=='y')
             {
                 temp=new Node();
                 System.out.println("Enter next data");
                 temp.data=Integer.parseInt(br.readLine());
                 temp.link=null;
                 ptr.link=temp;
                 temp=null;
                 ptr=ptr.link;
                }
            }while(ins=='y');
        }

public static void main(String args[])throws IOException
     {
       Node first= new Node();
       first.create();
}
}

What does %s mean in a python format string?

The format method was introduced in Python 2.6. It is more capable and not much more difficult to use:

>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.

>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'

>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'

>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'

Can not change UILabel text color

Try this one, where alpha is opacity and others is Red,Green,Blue chanels-

self.statusTextLabel.textColor = [UIColor colorWithRed:(233/255.f) green:(138/255.f) blue:(36/255.f) alpha:1];

Sum values in foreach loop php

You can use array_sum().

$total = array_sum($group);

Xcode : Adding a project as a build dependency

Xcode 10

  1. drag-n-drop a project into another project - is called cross-project references[About]
  2. add the added project as a build dependency - is called Explicit dependency[About]
//Xcode 10
Build Phases -> Target Dependencies -> + Add items 

//Xcode 11
Build Phases -> Dependencies -> + Add items 

In Choose items to add: dialog you will see only targets from your project and the sub-project

enter image description here

Array of an unknown length in C#

Use an ArrayList if in .NET 1.x, or a List<yourtype> if in .NET 2.0 or 3.x.

Search for them in System.Collections and System.Collections.Generics.

java.net.BindException: Address already in use: JVM_Bind <null>:80

PID 0 is the System Idle Process, which is surely not listening to port 80. How did you check which process was using the port?

You can use

netstat /nao | findstr "80"

to find the PID and check what process it is.

AngularJS sorting by property

Here is what i did and it works.
I just used a stringified object.

$scope.thread = [ 
  {
    mostRecent:{text:'hello world',timeStamp:12345678 } 
    allMessages:[]
  }
  {MoreThreads...}
  {etc....}
]

<div ng-repeat="message in thread | orderBy : '-mostRecent.timeStamp'" >

if i wanted to sort by text i would do

orderBy : 'mostRecent.text'

TempData keep() vs peek()

don't they both keep a value for another request?

Yes they do, but when the first one is void, the second one returns and object:

public void Keep(string key)
{
    _retainedKeys.Add(key); // just adds the key to the collection for retention
}

public object Peek(string key)
{
    object value;
    _data.TryGetValue(key, out value);
    return value; // returns an object without marking it for deletion
}

How do I search a Perl array for a matching string?

It depends on what you want the search to do:

  • if you want to find all matches, use the built-in grep:

    my @matches = grep { /pattern/ } @list_of_strings;
    
  • if you want to find the first match, use first in List::Util:

    use List::Util 'first';  
    my $match = first { /pattern/ } @list_of_strings;
    
  • if you want to find the count of all matches, use true in List::MoreUtils:

    use List::MoreUtils 'true';
    my $count = true { /pattern/ } @list_of_strings;
    
  • if you want to know the index of the first match, use first_index in List::MoreUtils:

    use List::MoreUtils 'first_index'; 
    my $index = first_index { /pattern/ } @list_of_strings;
    
  • if you want to simply know if there was a match, but you don't care which element it was or its value, use any in List::Util:

    use List::Util 1.33 'any';
    my $match_found = any { /pattern/ } @list_of_strings;
    

All these examples do similar things at their core, but their implementations have been heavily optimized to be fast, and will be faster than any pure-perl implementation that you might write yourself with grep, map or a for loop.


Note that the algorithm for doing the looping is a separate issue than performing the individual matches. To match a string case-insensitively, you can simply use the i flag in the pattern: /pattern/i. You should definitely read through perldoc perlre if you have not previously done so.

svn list of files that are modified in local copy

Below command will display the modfied files alone in windows.

svn status | findstr "^M"

Create Test Class in IntelliJ

  1. Right click on project then select new->directory. Create a new directory and name it "test".
  2. Right click on "test" folder then select Mark Directory As->Test Sources Root
  3. Click on Navigate->Test->Create New Test
    Select Testing library(JUnit4 or any)
    Specify Class Name
    Select Member

That's it. We can modify the directory structure as per our need. Good luck!

When to use Comparable and Comparator

If sorting of objects needs to be based on natural order then use Comparable whereas if your sorting needs to be done on attributes of different objects, then use Comparator in Java.

Main differences between Comparable and Comparator:

+------------------------------------------------------------------------------------+
¦               Comparable                ¦                Comparator                ¦
¦-----------------------------------------+------------------------------------------¦
¦ java.lang.Comparable                    ¦ java.util.Comparator                     ¦
¦-----------------------------------------+------------------------------------------¦
¦ int objOne.compareTo(objTwo)            ¦ int compare(objOne, objTwo)              ¦
¦-----------------------------------------+------------------------------------------¦
¦ Negative, if objOne < objTwo            ¦ Same as Comparable                       ¦
¦ Zero,  if objOne == objTwo              ¦                                          ¦
¦ Positive,  if objOne > objTwo           ¦                                          ¦
¦-----------------------------------------+------------------------------------------¦
¦ You must modify the class whose         ¦ You build a class separate from to sort. ¦
¦ instances you want to sort.             ¦ the class whose instances you want       ¦
¦-----------------------------------------+------------------------------------------¦
¦ Only one sort sequence can be created   ¦ Many sort sequences can be created       ¦
¦-----------------------------------------+------------------------------------------¦
¦ Implemented frequently in the API by:   ¦ Meant to be implemented to sort          ¦
¦ String, Wrapper classes, Date, Calendar ¦ instances of third-party classes.        ¦
+------------------------------------------------------------------------------------+

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:

module.directive('myDirectiveContainer', function () {
    return {
        controller: function ($scope) {
            this.scope = $scope;
        }
    };
});

module.directive('myDirective', function () {
    return {
        require: '^myDirectiveContainer',
        link: function (scope, element, attrs, containerController) {
            // use containerController.scope here...
        }
    };
});

and then

<div my-directive-container="">
    <div my-directive="">
    </div>
</div>

Maybe not the most graceful solution, but it got the job done.

JPA: how do I persist a String into a database field, type MYSQL Text

With @Lob I always end up with a LONGTEXTin MySQL.

To get TEXT I declare it that way (JPA 2.0):

@Column(columnDefinition = "TEXT")
private String text

Find this better, because I can directly choose which Text-Type the column will have in database.

For columnDefinition it is also good to read this.

EDIT: Please pay attention to Adam Siemions comment and check the database engine you are using, before applying columnDefinition = "TEXT".

LINQ: "contains" and a Lambda query

I'm not sure precisely what you're looking for, but this program:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public StatusType Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = Building.StatusType.open },
        new Building () { Name = "two", Status = Building.StatusType.closed },
        new Building () { Name = "three", Status = Building.StatusType.weird },

        new Building () { Name = "four", Status = Building.StatusType.open },
        new Building () { Name = "five", Status = Building.StatusType.closed },
        new Building () { Name = "six", Status = Building.StatusType.weird },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };

        var q = from building in buildingList
                where statusList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);
    }

produces the expected output:

one: open
two: closed
four: open
five: closed

This program compares a string representation of the enum and produces the same output:

    public class Building
    {
        public enum StatusType
        {
            open,
            closed,
            weird,
        };

        public string Name { get; set; }
        public string Status { get; set; }
    }

    public static List <Building> buildingList = new List<Building> ()
    {
        new Building () { Name = "one", Status = "open" },
        new Building () { Name = "two", Status = "closed" },
        new Building () { Name = "three", Status = "weird" },

        new Building () { Name = "four", Status = "open" },
        new Building () { Name = "five", Status = "closed" },
        new Building () { Name = "six", Status = "weird" },
    };

    static void Main (string [] args)
    {
        var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
        var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());

        var q = from building in buildingList
                where statusStringList.Contains (building.Status)
                select building;

        foreach ( var b in q )
            Console.WriteLine ("{0}: {1}", b.Name, b.Status);

        Console.ReadKey ();
    }

I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.

public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
    foreach ( TSource source in sources )
        yield return convert (source);
}

Then you can change the where clause to:

where statusList.ConvertEach <string> (status => status.GetCharValue()).
    Contains (v.Status)

and skip creating the List<string> with ConvertAll () at the beginning.

How generate unique Integers based on GUIDs

In a static class, keep a static const integer, then add 1 to it before every single access (using a public get property). This will ensure you cycle the whole int range before you get a non-unique value.

    /// <summary>
    /// The command id to use. This is a thread-safe id, that is unique over the lifetime of the process. It changes
    /// at each access.
    /// </summary>
    internal static int NextCommandId
    {
        get
        {
            return _nextCommandId++;
        }
    }       
    private static int _nextCommandId = 0;

This will produce a unique integer value within a running process. Since you do not explicitly define how unique your integer should be, this will probably fit.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I got the same error because I created a new object from a templated class using the template name without specifying the type explicitly like this:

int main()
{

    MyClass<T> Test2(5.60, 6.6); <- This is wrong
           ^^^
    return 0;
}

The correct way to do it was to specify exactly what T was like this:

int main()
{

    MyClass<double> Test2(5.60, 6.6); <- This is right
            ^^^^^^
    return 0;
}

How to deal with persistent storage (e.g. databases) in Docker

In case it is not clear from update 5 of the selected answer, as of Docker 1.9, you can create volumes that can exist without being associated with a specific container, thus making the "data-only container" pattern obsolete.

See Data-only containers obsolete with docker 1.9.0? #17798.

I think the Docker maintainers realized the data-only container pattern was a bit of a design smell and decided to make volumes a separate entity that can exist without an associated container.

How to convert List<Integer> to int[] in Java?

If you are simply mapping an Integer to an int then you should consider using parallelism, since your mapping logic does not rely on any variables outside its scope.

int[] arr = list.parallelStream().mapToInt(Integer::intValue).toArray();

Just be aware of this

Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.


There are two ways to map Integers to their primitive form:

  1. Via a ToIntFunction.

    mapToInt(Integer::intValue)
    
  2. Via explicit unboxing with lambda expression.

    mapToInt(i -> i.intValue())
    
  3. Via implicit (auto-) unboxing with lambda expression.

    mapToInt(i -> i)
    

Given a list with a null value

List<Integer> list = Arrays.asList(1, 2, null, 4, 5);

Here are three options to handle null:

  1. Filter out the null values before mapping.

    int[] arr = list.parallelStream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray();
    
  2. Map the null values to a default value.

    int[] arr = list.parallelStream().map(i -> i == null ? -1 : i).mapToInt(Integer::intValue).toArray();
    
  3. Handle null inside the lambda expression.

    int[] arr = list.parallelStream().mapToInt(i -> i == null ? -1 : i.intValue()).toArray();
    

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

Convert string to date then format the date

In one line:

String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));

Where:

String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));

Cannot install packages inside docker Ubuntu image

You need to update the package list in your Ubuntu:

$ sudo apt-get update
$ sudo apt-get install <package_name>

Angular2: Cannot read property 'name' of undefined

You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

Specifically, under the heading Display hero names in a template, it states:

To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

followed by this code block:

<h2>My Heroes</h2>
<ul class="heroes">
  <li>
    <!-- each hero goes here -->
  </li>
</ul>

It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

<h2>{{hero.name}} details!</h2>

outside of our *ngFor.

However, if you scroll further down the page, you will encounter the following:

The template for displaying heroes should look like this:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Note the absence of the detail elements from previous efforts.

An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.

Why .NET String is immutable?

Just to throw this in, an often forgotten view is of security, picture this scenario if strings were mutable:

string dir = "C:\SomePlainFolder";

//Kick off another thread
GetDirectoryContents(dir);

void GetDirectoryContents(string directory)
{
  if(HasAccess(directory) {
    //Here the other thread changed the string to "C:\AllYourPasswords\"
    return Contents(directory);
  }
  return null;
}

You see how it could be very, very bad if you were allowed to mutate strings once they were passed.

c# write text on bitmap

var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
    g.DrawString( ... );
}

picturebox1.Image = bmp;

How to avoid precompiled headers

You can create an empty project by selecting the "Empty Project" from the "General" group of Visual C++ projects (maybe that project template isn't included in Express?).

To fix the problem in the project you already have, open the project properties and navigate to:

Configuration Properties | C/C++ | Precompiled Headers

And choose "Not using Precompiled Headers" for the "Precompiled Header" option.

Reset local repository branch to be just like remote repository HEAD

Previous answers assume that the branch to be reset is the current branch (checked out). In comments, OP hap497 clarified that the branch is indeed checked out, but this is not explicitly required by the original question. Since there is at least one "duplicate" question, Reset branch completely to repository state, which does not assume that the branch is checked out, here's an alternative:

If branch "mybranch" is not currently checked out, to reset it to remote branch "myremote/mybranch"'s head, you can use this low-level command:

git update-ref refs/heads/mybranch myremote/mybranch

This method leaves the checked out branch as it is, and the working tree untouched. It simply moves mybranch's head to another commit, whatever is given as the second argument. This is especially helpful if multiple branches need to be updated to new remote heads.

Use caution when doing this, though, and use gitk or a similar tool to double check source and destination. If you accidentally do this on the current branch (and git will not keep you from this), you may become confused, because the new branch content does not match the working tree, which did not change (to fix, update the branch again, to where it was before).

Python: split a list based on a condition?

itertools.groupby almost does what you want, except it requires the items to be sorted to ensure that you get a single contiguous range, so you need to sort by your key first (otherwise you'll get multiple interleaved groups for each type). eg.

def is_good(f):
    return f[2].lower() in IMAGE_TYPES

files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file3.gif', 123L, '.gif')]

for key, group in itertools.groupby(sorted(files, key=is_good), key=is_good):
    print key, list(group)

gives:

False [('file2.avi', 999L, '.avi')]
True [('file1.jpg', 33L, '.jpg'), ('file3.gif', 123L, '.gif')]

Similar to the other solutions, the key func can be defined to divide into any number of groups you want.

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

What's the difference between returning value or Promise.resolve from then()

The rule is, if the function that is in the then handler returns a value, the promise resolves/rejects with that value, and if the function returns a promise, what happens is, the next then clause will be the then clause of the promise the function returned, so, in this case, the first example falls through the normal sequence of the thens and prints out values as one might expect, in the second example, the promise object that gets returned when you do Promise.resolve("bbb")'s then is the then that gets invoked when chaining(for all intents and purposes). The way it actually works is described below in more detail.

Quoting from the Promises/A+ spec:

The promise resolution procedure is an abstract operation taking as input a promise and a value, which we denote as [[Resolve]](promise, x). If x is a thenable, it attempts to make promise adopt the state of x, under the assumption that x behaves at least somewhat like a promise. Otherwise, it fulfills promise with the value x.

This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.

The key thing to notice here is this line:

if x is a promise, adopt its state [3.4]

link: https://promisesaplus.com/#point-49

Adding files to java classpath at runtime

yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

Dump all documents of Elasticsearch

We can use elasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.

1. Commands to move one index data from one server/cluster to another using elasticdump.

# Copy an index from production to staging with analyzer and mapping:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=analyzer
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

2. Commands to move all indices data from one server/cluster to another using multielasticdump.

Backup

multielasticdump \
  --direction=dump \
  --match='^.*$' \
  --limit=10000 \
  --input=http://production.es.com:9200 \
  --output=/tmp 

Restore

multielasticdump \
  --direction=load \
  --match='^.*$' \
  --limit=10000 \
  --input=/tmp \
  --output=http://staging.es.com:9200 

Note:

  • If the --direction is dump, which is the default, --input MUST be a URL for the base location of an ElasticSearch server (i.e. http://localhost:9200) and --output MUST be a directory. Each index that does match will have a data, mapping, and analyzer file created.

  • For loading files that you have dumped from multi-elasticsearch, --direction should be set to load, --input MUST be a directory of a multielasticsearch dump and --output MUST be a Elasticsearch server URL.

  • The 2nd command will take a backup of settings, mappings, template and data itself as JSON files.

  • The --limit should not be more than 10000 otherwise, it will give an exception.

  • Get more details here.

How do I display a wordpress page content?

@Sydney Try putting wp_reset_query() before you call the loop. This will display the content of your page.

<?php
    wp_reset_query(); // necessary to reset query
    while ( have_posts() ) : the_post();
        the_content();
    endwhile; // End of the loop.
?>

EDIT: Try this if you have some other loops that you previously ran. Place wp_reset_query(); where you find it most suitable, but before you call this loop.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Rather than doing string manipulation, you can use the HOUR, MINUTE, SECOND functions to break apart the time. You can then multiply by 60*60*1000, 60*1000, and 1000 respectively to get milliseconds.

Python - Create list with numbers between 2 values?

The most elegant way to do this is by using the range function however if you want to re-create this logic you can do something like this :

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

This produces the output:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the range or numpy.arrange however I find the code interesting to be shared.

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

Left padding a String with Zeros

If you need performance and know the maximum size of the string use this:

String zeroPad = "0000000000000000";
String str0 = zeroPad.substring(str.length()) + str;

Be aware of the maximum string size. If it is bigger then the StringBuffer size, you'll get a java.lang.StringIndexOutOfBoundsException.

How do I size a UITextView to its content?

We can do it by constraints .

  1. Set Height constraints for UITextView. enter image description here

2.Create IBOutlet for that height constraint.

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;

3.don't forget to set delegate for your textview.

4.

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
    [UIView animateWithDuration:0.2 animations:^{
                  _txtheightconstraints.constant=newFrame.size.height;
    }];

}

then update your constraint like this :)

How do I access refs of a child component in the parent component

  1. Inside the child component add a ref to the node you need
  2. Inside the parent component add a ref to the child component.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

JavaScript hide/show element

Though this question has been answered many times before, I thought I would add to it with a more complete and solid answer for future users. The main answer does solve the problem, but I believe it may be better to know/understand the some of various ways to show/hide things.

.

Changing display using css()

This is the way I used to do it until I found some of these other ways.

Javascript:

$("#element_to_hide").css("display", "none");  // To hide
$("#element_to_hide").css("display", "");  // To unhide

Pros:

  • Hides and unhides. That's about it.

Cons:

  • If you use the "display" attribute for something else, you will have to hardcode the value of what it was prior to hiding. So if you had "inline", you would have to do $("#element_to_hid").css("display", "inline"); otherwise it will default back to "block" or whatever else that it will be forced into.
  • Lends itself to typos.

Example: https://jsfiddle.net/4chd6e5r/1/

.

Changing display using addClass()/removeClass()

While setting up the example for this one, I actually ran into some flaws on this method that make it very very unreliable.

Css/Javascript:

.hidden {display:none}
$("#element_to_hide").addClass("hidden");  // To hide
$("#element_to_hide").removeClass("hidden");  // To unhide

Pros:

  • It hides....sometimes. Refer to p1 on the example.
  • After unhiding, it will return back to using the previous display value....sometimes. Refer to p1 on the example.
  • If you want to grab all hidden objects, you just need to do $(".hidden").

Cons:

  • Does not hide if the display value was set directly on the html. Refer to p2 on the example.
  • Does not hide if the display is set in javascript using css(). Refer to p3 on the example.
  • Slightly more code because you have to define a css attribute.

Example: https://jsfiddle.net/476oha8t/8/

.

Changing display using toggle()

Javascript:

$("element_to_hide").toggle();  // To hide and to unhide

Pros:

  • Always works.
  • Allows you to not have to worry about which state it was prior to switching. The obvious use for this is for a....toggle button.
  • Short and simple.

Cons:

  • If you need to know which state it is switching to in order to do something not directly related, you will have to add more code (an if statement) to find out which state it is in.
  • Similar to the previous con, if you want to run a set of instructions that contains the toggle() for the purpose of hiding, but you don't know if it is already hidden, you have to add a check (an if statement) to find out first and if it is already hidden, then skip. Refer to p1 of the example.
  • Related to the previous 2 cons, using toggle() for something that is specifically hiding or specifically showing, can be confusing to others reading your code as they do not know which way they will toggle.

Example: https://jsfiddle.net/cxcawkyk/1/

.

Changing display using hide()/show()

Javascript:

$("#element_to_hide").hide();  // To hide
$("#element_to_hide").show();  // To show

Pros:

  • Always works.
  • After unhiding, it will return back to using the previous display value.
  • You will always know which state you are swapping to so you:
    1. don't need to add if statements to check visibility before changing states if the state matters.
    2. won't confuse others reading your code as to which state you are switching to if, if the state matters.
  • Intuitive.

Cons:

  • If you want to imitate a toggle, you will have to check the state first and then switch to the other state. Use toggle() instead for these. Refer to p2 of the example.

Example: https://jsfiddle.net/k0ukhmfL/

.

Overall, I would say the best to be hide()/show() unless you specifically need it to be a toggle. I hope you found this information to be helpful.

How do I convert a PDF document to a preview image in PHP?

You need ImageMagick and GhostScript

<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

The [0] means page 1.

Cast object to T

Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):

private static T ReadData<T>(XmlReader reader, string value) where T : class
{
    reader.MoveToAttribute(value);
    object readData = reader.ReadContentAsObject();
    return (T)readData;
}

or where T : IMyInterface or where T : new(), etc

How to use `subprocess` command with pipes

command = "ps -A | grep 'process_name'"
output = subprocess.check_output(["bash", "-c", command])

AngularJS: Basic example to use authentication in Single Page Application

I like the approach and implemented it on server-side without doing any authentication related thing on front-end

My 'technique' on my latest app is.. the client doesn't care about Auth. Every single thing in the app requires a login first, so the server just always serves a login page unless an existing user is detected in the session. If session.user is found, the server just sends index.html. Bam :-o

Look for the comment by "Andrew Joslin".

https://groups.google.com/forum/?fromgroups=#!searchin/angular/authentication/angular/POXLTi_JUgg/VwStpoWCPUQJ

What is an NP-complete in computer science?

We need to separate algorithms and problems. We write algorithms to solve problems, and they scale in a certain way. Although this is a simplification, let's label an algorithm with a 'P' if the scaling is good enough, and 'NP' if it isn't.

It's helpful to know things about the problems we're trying to solve, rather than the algorithms we use to solve them. So we'll say that all the problems which have a well-scaling algorithm are "in P". And the ones which have a poor-scaling algorithm are "in NP".

That means that lots of simple problems are "in NP" too, because we can write bad algorithms to solve easy problems. It would be good to know which problems in NP are the really tricky ones, but we don't just want to say "it's the ones we haven't found a good algorithm for". After all, I could come up with a problem (call it X) that I think needs a super-amazing algorithm. I tell the world that the best algorithm I could come up with to solve X scales badly, and so I think that X is a really tough problem. But tomorrow, maybe somebody cleverer than me invents an algorithm which solves X and is in P. So this isn't a very good definition of hard problems.

All the same, there are lots of problems in NP that nobody knows a good algorithm for. So if I could prove that X is a certain sort of problem: one where a good algorithm to solve X could also be used, in some roundabout way, to give a good algorithm for every other problem in NP. Well now people might be a bit more convinced that X is a genuinely tricky problem. And in this case we call X NP-Complete.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

What's the difference between .NET Core, .NET Framework, and Xamarin?

  1. .NET is the Ecosystem based on c# language
  2. .NET Standard is Standard (in other words, specification) of .NET Ecosystem .

.Net Core Class Library is built upon the .Net Standard. .NET Standard you can make only class-library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.If you want to implement a library that is portable to the .Net Framework, .Net Core and Xamarin, choose a .Net Standard Library

  1. .NET Framework is a framework based on .NET and it supports Windows and Web applications

(You can make executable project (like Console application, or ASP.NET application) with .NET Framework

  1. ASP.NET is a web application development technology which is built over the .NET Framework
  2. .NET Core also a framework based on .NET.

It is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux.

  1. Xamarin is a framework to develop a cross platform mobile application(iOS, Android, and Windows Mobile) using C#

Implementation support of .NET Standard[blue] and minimum viable platform for full support of .NET Standard (latest: [https://docs.microsoft.com/en-us/dotnet/standard/net-standard#net-implementation-support])

Extract data from XML Clob using SQL from Oracle Database

Try

SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]') 
FROM traptabclob;

Here is a sqlfiddle demo

Cheap way to search a large text file for a string

If it is "pretty large" file, then access the lines sequentially and don't read the whole file into memory:

with open('largeFile', 'r') as inF:
    for line in inF:
        if 'myString' in line:
            # do_something

How to get all selected values of a multiple select box?

Check-it Out:

HTML:

<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server"  SelectionMode="Multiple" Width="100px">
    <asp:ListItem Text="Raj" Value="1"></asp:ListItem>
    <asp:ListItem Text="Karan" Value="2"></asp:ListItem>
    <asp:ListItem Text="Riya" Value="3"></asp:ListItem>
    <asp:ListItem Text="Aman" Value="4"></asp:ListItem>
    <asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>

JQUERY:

$("#aSelect").click(function(){
    var selectedValues = [];    
    $("#lstSelect :selected").each(function(){
        selectedValues.push($(this).val()); 
    });
    alert(selectedValues);
    return false;
});

CLICK HERE TO SEE THE DEMO

Change size of axes title and labels in ggplot2

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.

Displaying a message in iOS which has the same functionality as Toast in Android

Swift 4

How about this small trick?

func showToast(controller: UIViewController, message : String, seconds: Double) {
    let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
    alert.view.backgroundColor = UIColor.black
    alert.view.alpha = 0.6
    alert.view.layer.cornerRadius = 15

    controller.present(alert, animated: true)

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds) {
        alert.dismiss(animated: true)
    }
}

Example of calling:

showToast(controller: self, message : "This is a test", seconds: 2.0)

Output:

Android emulator: How to monitor network traffic?

You can use http://docs.mitmproxy.org/en/stable/install.html

Its easy to setup and won't require any extra tweaks.

I go through various tool but found it to be really good and easy.

The meaning of NoInitialContextException error

Do this:

Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
Context initialContext = new InitialContext(props);

Also add this to the libraries of the project:

C:\installs\glassfish\glassfish-4.1\glassfish\lib\gf-client.jar adjust path accordingly

Why do some functions have underscores "__" before and after the function name?

Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:

class ThreadableMixin:
   def start_worker(self):
       threading.Thread(target=self.worker).start()

   def worker(self):
      try:
        self._worker()
    except tornado.web.HTTPError, e:
        self.set_status(e.status_code)
    except:
        logging.error("_worker problem", exc_info=True)
        self.set_status(500)
    tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))

...

and the child that have a _worker method

class Handler(tornado.web.RequestHandler, ThreadableMixin):
   def _worker(self):
      self.res = self.render_string("template.html",
        title = _("Title"),
        data = self.application.db.query("select ... where object_id=%s", self.object_id)
    )

...

Python "\n" tag extra line

This:

    print "\n"

is printing out two \n characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a , like you use in print a,. Simply use

    print

instead.

How do I sort a Set to a List in Java?

List myList = new ArrayList(collection);
Collections.sort(myList);

… should do the trick however. Add flavour with Generics where applicable.

Adding blur effect to background in swift

U can also use CoreImage to create blurred image with dark effect

  1. Make snapshot for image

    func snapShotImage() -> UIImage {
        UIGraphicsBeginImageContext(self.frame.size)
        if let context = UIGraphicsGetCurrentContext() {
            self.layer.renderInContext(context)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    
        return UIImage()
    }
    
  2. Apply CoreImage Filters as u wish with

    private func bluredImage(view:UIView, radius:CGFloat = 1) -> UIImage {
    let image = view.snapShotImage()
    
    if let source = image.CGImage {
        let context = CIContext(options: nil)
        let inputImage = CIImage(CGImage: source)
    
        let clampFilter = CIFilter(name: "CIAffineClamp")
        clampFilter?.setDefaults()
        clampFilter?.setValue(inputImage, forKey: kCIInputImageKey)
    
        if let clampedImage = clampFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
            let explosureFilter = CIFilter(name: "CIExposureAdjust")
            explosureFilter?.setValue(clampedImage, forKey: kCIInputImageKey)
            explosureFilter?.setValue(-1.0, forKey: kCIInputEVKey)
    
            if let explosureImage = explosureFilter?.valueForKey(kCIOutputImageKey) as? CIImage {
                let filter = CIFilter(name: "CIGaussianBlur")
                filter?.setValue(explosureImage, forKey: kCIInputImageKey)
                filter?.setValue("\(radius)", forKey:kCIInputRadiusKey)
    
                if let result = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
                    let bounds = UIScreen.mainScreen().bounds
                    let cgImage = context.createCGImage(result, fromRect: bounds)
                    let returnImage = UIImage(CGImage: cgImage)
                    return returnImage
                }
            }
        }
    }
    return UIImage()
    }
    

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

Could not load type from assembly error

Deleting my .pdb file for the dll solved this issue for me. I'm guessing it has something to do with the fact that the dll was created using ILMerge.

Good Java graph algorithm library?

If you need performance, you might take a look at Grph. The library is developed in the French University and CNRS/Inria.

http://www.i3s.unice.fr/~hogie/grph/

The project is active and reactive support is provided!

numbers not allowed (0-9) - Regex Expression in javascript

Something as simple as [a-z]+, or perhaps [\S]+, or even [a-zA-Z]+?

How to disable input conditionally in vue.js

To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.

So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:

<input type="text" :disabled="validated == 1">

Here is an example.

_x000D_
_x000D_
var app = new Vue({_x000D_
  el: '#app',_x000D_
_x000D_
  data: {_x000D_
    disabled: 0,_x000D_
  },_x000D_
}); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="app">_x000D_
  <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>_x000D_
  <input type="text" :disabled="disabled == 1">_x000D_
    _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I change the current URL?

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

  1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

    $(window).bind("popstate", function(e) { alert("location changed"); });

    Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

How to change target build on Android project?

Well I agree with Ryan Conrad on how to do it in eclipse, have you ensured you have changed your manifest.xml?

 <uses-sdk android:minSdkVersion="3" />
 <uses-sdk android:targetSdkVersion="8" />

How to show google.com in an iframe?

Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

Table Height 100% inside Div element

This is how you can do it-

HTML-

<div style="overflow:hidden; height:100%">
     <div style="float:left">a<br>b</div>
     <table cellpadding="0" cellspacing="0" style="height:100%;">     
          <tr><td>This is the content of a table that takes 100% height</td></tr>  
      </table>
 </div>

CSS-

html,body
{
    height:100%;
    background-color:grey;
}
table
{
    background-color:yellow;
}

See the DEMO

Update: Well, if you are not looking for applying 100% height to your parent containers, then here is a jQuery solution that should help you-

Demo-using jQuery

Script-

 $(document).ready(function(){
    var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
    $("#tab").css("height",b);
});

How to inspect FormData?

  function abc(){ 
    var form = $('#form_name')[0]; 
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) { 
            console.log(key, value);
        }
        $.ajax({
            type: "POST",
            url: " ",
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {

            },
            success: function(data) {


            },

       });
}

Why is &#65279; appearing in my HTML?

Try:

<?php 
// Tell me the root folder path.
// You can also try this one
// $HOME = $_SERVER["DOCUMENT_ROOT"];
// Or this
// dirname(__FILE__)
$HOME = dirname(__FILE__);

// Is this a Windows host ? If it is, change this line to $WIN = 1;
$WIN = 0;

// That's all I need
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF8 BOM FINDER and REMOVER</title>
<style>
body { font-size: 10px; font-family: Arial, Helvetica, sans-serif; background: #FFF; color: #000; }
.FOUND { color: #F30; font-size: 14px; font-weight: bold; }
</style>
</head>
<body>
<?php
$BOMBED = array();
RecursiveFolder($HOME);
echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';
foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }
echo '</p>';

// Recursive finder
function RecursiveFolder($sHOME) {
  global $BOMBED, $WIN;

  $win32 = ($WIN == 1) ? "\\" : "/";

  $folder = dir($sHOME);

  $foundfolders = array();
  while ($file = $folder->read()) {
    if($file != "." and $file != "..") {
      if(filetype($sHOME . $win32 . $file) == "dir"){
        $foundfolders[count($foundfolders)] = $sHOME . $win32 . $file;
      } else {
        $content = file_get_contents($sHOME . $win32 . $file);
        $BOM = SearchBOM($content);
        if ($BOM) {
          $BOMBED[count($BOMBED)] = $sHOME . $win32 . $file;

          // Remove first three chars from the file
          $content = substr($content,3);
          // Write to file 
          file_put_contents($sHOME . $win32 . $file, $content);
        }
      }
    }
  }
  $folder->close();

  if(count($foundfolders) > 0) {
    foreach ($foundfolders as $folder) {
      RecursiveFolder($folder, $win32);
    }
  }
}

// Searching for BOM in files
function SearchBOM($string) { 
    if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;
    return false; 
}
?>
</body>
</html>

copy this code to php file upload to root and run it.

for more about this: http://forum.virtuemart.net/index.php?topic=98700.0

Convert generic List/Enumerable to DataTable?

This link on MSDN is worth a visit: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow

This adds an extension method that lets you do this:

// Create a sequence. 
Item[] items = new Item[] 
{ new Book{Id = 1, Price = 13.50, Genre = "Comedy", Author = "Gustavo Achong"}, 
  new Book{Id = 2, Price = 8.50, Genre = "Drama", Author = "Jessie Zeng"},
  new Movie{Id = 1, Price = 22.99, Genre = "Comedy", Director = "Marissa Barnes"},
  new Movie{Id = 1, Price = 13.40, Genre = "Action", Director = "Emmanuel Fernandez"}};

// Query for items with price greater than 9.99.
var query = from i in items
             where i.Price > 9.99
             orderby i.Price
             select i;

// Load the query results into new DataTable.
DataTable table = query.CopyToDataTable();

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

Automatic vertical scroll bar in WPF TextBlock?

Dont know if someone else has this problem but wrapping my TextBlock into a ScrollViewer somewhow messed up my UI - as a simple workaround I figured out that replacing the TextBlock by a TextBox like this one

<TextBox  Name="textBlock" SelectionBrush="Transparent" Cursor="Arrow" IsReadOnly="True" Text="My Text" VerticalScrollBarVisibility="Auto">

creates a TextBox that looks and behaves like a TextBlock with a scrollbar (and you can do it all in the designer).

Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server

Just find a better way to do that from your hosting control panel (I'm using DirectAdmin here)

simply go to the target server DB in your control panel, in my case: MySQL management -> select your DB -> you will find: "Access Hosts", simply add your remote host here and its working now! enter image description here

I guess there is a similar option on other C.panels like plesk, etc..

I'm hope it was helpful to you too.

redirect COPY of stdout to log file from within bash script itself

Inside your script file, put all of the commands within parentheses, like this:

(
echo start
ls -l
echo end
) | tee foo.log

For each row return the column name of the largest value

If you're interested in a data.table solution, here's one. It's a bit tricky since you prefer to get the id for the first maximum. It's much easier if you'd rather want the last maximum. Nevertheless, it's not that complicated and it's fast!

Here I've generated data of your dimensions (26746 * 18).

Data

set.seed(45)
DF <- data.frame(matrix(sample(10, 26746*18, TRUE), ncol=18))

data.table answer:

require(data.table)
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]

Benchmarking:

# data.table solution
system.time({
DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid), DT[J(unique(colid)), value, mult="last"]), rowid, mult="first"]
})
#   user  system elapsed 
#  0.174   0.029   0.227 

# apply solution from @thelatemail
system.time(t2 <- colnames(DF)[apply(DF,1,which.max)])
#   user  system elapsed 
#  2.322   0.036   2.602 

identical(t1, t2)
# [1] TRUE

It's about 11 times faster on data of these dimensions, and data.table scales pretty well too.


Edit: if any of the max ids is okay, then:

DT <- data.table(value=unlist(DF, use.names=FALSE), 
            colid = 1:nrow(DF), rowid = rep(names(DF), each=nrow(DF)))
setkey(DT, colid, value)
t1 <- DT[J(unique(colid)), rowid, mult="last"]

How do I get Flask to run on port 80?

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

How to bring a window to the front?

Windows has the facility to prevent windows from stealing focus; instead it flashes the taskbar icon. In XP it's on by default (the only place I've seen to change it is using TweakUI, but there is a registry setting somewhere). In Vista they may have changed the default and/or exposed it as a user accessible setting with the out-of-the-box UI.

Preventing windows from forcing themselves to the front and taking focus is a feature since Windows 2K (and I, for one, am thankful for it).

That said, I have a little Java app I use to remind me to record my activities while working, and it makes itself the active window every 30 minutes (configurable, of course). It always works consistently under Windows XP and never flashes the title bar window. It uses the following code, called in the UI thread as a result of a timer event firing:

if(getState()!=Frame.NORMAL) { setState(Frame.NORMAL); }
toFront();
repaint();

(the first line restores if minimized... actually it would restore it if maximized too, but I never have it so).

While I usually have this app minimized, quite often it's simply behind my text editor. And, like I said, it always works.

I do have an idea on what your problem could be - perhaps you have a race condition with the setVisible() call. toFront() may not be valid unless the window is actually displayed when it is called; I have had this problem with requestFocus() before. You may need to put the toFront() call in a UI listener on a window activated event.

2014-09-07: At some point in time the above code stopped working, perhaps at Java 6 or 7. After some investigation and experimentation I had to update the code to override the window's toFront method do this (in conjunction with modified code from what is above):

setVisible(true);
toFront();
requestFocus();
repaint();

...

public @Override void toFront() {
    int sta = super.getExtendedState() & ~JFrame.ICONIFIED & JFrame.NORMAL;

    super.setExtendedState(sta);
    super.setAlwaysOnTop(true);
    super.toFront();
    super.requestFocus();
    super.setAlwaysOnTop(false);
}

As of Java 8_20, this code seems to be working fine.

How to scale a BufferedImage

If you do not mind using an external library, Thumbnailator can perform scaling of BufferedImages.

Thumbnailator will take care of handling the Java 2D processing (such as using Graphics2D and setting appropriate rendering hints) so that a simple fluent API call can be used to resize images:

BufferedImage image = Thumbnails.of(originalImage).scale(2.0).asBufferedImage();

Although Thumbnailator, as its name implies, is geared toward shrinking images, it will do a decent job enlarging images as well, using bilinear interpolation in its default resizer implementation.


Disclaimer: I am the maintainer of the Thumbnailator library.

How can I tell when a MySQL table was last updated?

I'm surprised no one has suggested tracking last update time per row:

mysql> CREATE TABLE foo (
  id INT PRIMARY KEY
  x INT,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP 
                     ON UPDATE CURRENT_TIMESTAMP,
  KEY (updated_at)
);

mysql> INSERT INTO foo VALUES (1, NOW() - INTERVAL 3 DAY), (2, NOW());

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | NULL | 2013-08-18 03:26:28 |
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

mysql> UPDATE foo SET x = 1234 WHERE id = 1;

This updates the timestamp even though we didn't mention it in the UPDATE.

mysql> SELECT * FROM foo;
+----+------+---------------------+
| id | x    | updated_at          |
+----+------+---------------------+
|  1 | 1235 | 2013-08-21 03:30:20 | <-- this row has been updated
|  2 | NULL | 2013-08-21 03:26:28 |
+----+------+---------------------+

Now you can query for the MAX():

mysql> SELECT MAX(updated_at) FROM foo;
+---------------------+
| MAX(updated_at)     |
+---------------------+
| 2013-08-21 03:30:20 |
+---------------------+

Admittedly, this requires more storage (4 bytes per row for TIMESTAMP).
But this works for InnoDB tables before 5.7.15 version of MySQL, which INFORMATION_SCHEMA.TABLES.UPDATE_TIME doesn't.

Creating and writing lines to a file

Set objFSO=CreateObject("Scripting.FileSystemObject")

' How to write file
outFile="c:\test\autorun.inf"
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write "test string" & vbCrLf
objFile.Close

'How to read a file
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine= objFile.ReadLine
    Wscript.Echo strLine
Loop
objFile.Close

'to get file path without drive letter, assuming drive letters are c:, d:, etc
strFile="c:\test\file"
s = Split(strFile,":")
WScript.Echo s(1)

How to write unit testing for Angular / TypeScript for private methods with Jasmine

Sorry for the necro on this post, but I feel compelled to weigh in on a couple of things that do not seem to have been touched on.

First a foremost - when we find ourselves needing access to private members on a class during unit testing, it is generally a big, fat red flag that we've goofed in our strategic or tactical approach and have inadvertently violated the single responsibility principal by pushing behavior where it does not belong. Feeling the need to access methods that are really nothing more than an isolated subroutine of a construction procedure is one of the most common occurrences of this; however, it's kind of like your boss expecting you to show up for work ready-to-go and also having some perverse need to know what morning routine you went through to get you into that state...

The other most common instance of this happening is when you find yourself trying to test the proverbial "god class." It is a special kind of problem in and of itself, but suffers from the same basic issue with needing to know intimate details of a procedure - but that's getting off topic.

In this specific example, we've effectively assigned the responsibility of fully initializing the Bar object to the FooBar class's constructor. In object oriented programming, one of the core tenents is that the constructor is "sacred" and should be guarded against invalid data that would invalidate its' own internal state and leave it primed to fail somewhere else downstream (in what could be a very deep pipeline.)

We've failed to do that here by allowing the FooBar object to accept a Bar that is not ready at the time that the FooBar is constructed, and have compensated by sort-of "hacking" the FooBar object to take matters into its' own hands.

This is the result of a failure to adhere to another tenent of object oriented programming (in the case of Bar,) which is that an object's state should be fully initialized and ready to handle any incoming calls to its' public members immediately after creation. Now, this does not mean immediately after the constructor is called in all instances. When you have an object that has many complex construction scenarios, then it is better to expose setters to its optional members to an object that is implemented in accordance with a creation design-pattern (Factory, Builder, etc...) In any of the latter cases, you would be pushing the initialization of the target object off into another object graph whose sole purpose is directing traffic to get you to a point where you have a valid instance of that which you are requesting - and the product should not be considered "ready" until after this creation object has served it up.

In your example, the Bar's "status" property does not seem to be in a valid state in which a FooBar can accept it - so the FooBar does something to it to correct that issue.

The second issue I am seeing is that it appears that you are trying to test your code rather than practice test-driven development. This is definitely my own opinion at this point in time; but, this type of testing is really an anti-pattern. What you end up doing is falling into the trap of realizing that you have core design problems that prevent your code from being testable after the fact, rather than writing the tests you need and subsequently programming to the tests. Either way you come at the problem, you should still end up with the same number of tests and lines of code had you truly achieved a SOLID implementation. So - why try and reverse engineer your way into testable code when you can just address the matter at the onset of your development efforts?

Had you done that, then you would have realized much earlier on that you were going to have to write some rather icky code in order to test against your design and would have had the opportunity early on to realign your approach by shifting behavior to implementations that are easily testable.

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Use the Moment.js library http://momentjs.com/ It will save you a LOT of trouble.

moment().format('DD-MMM-YYYY');

How to add Class in <li> using wp_nav_menu() in Wordpress?

Adding Class to <li> tag without editing functions.php file:

  1. Go to Appearance -> Menu -> Screen Options -> CSS Classes
  2. You will get CSS Class option enabled in Menu Items Window

enter image description here

How to Upload Image file in Retrofit 2

For those with an inputStream, you can upload inputStream using Multipart.

@Multipart
@POST("pictures")
suspend fun uploadPicture(
        @Part part: MultipartBody.Part
): NetworkPicture

Then in perhaps your repository class:

suspend fun upload(inputStream: InputStream) {
   val part = MultipartBody.Part.createFormData(
         "pic", "myPic", RequestBody.create(
              MediaType.parse("image/*"),
              inputStream.readBytes()
          )
   )
   uploadPicture(part)
}

To get an input stream you can do something like so.

In your fragment or activity, you need to create an image picker that returns an InputStream. The advantage of an InputStream is that it can be used for files on the cloud like google drive and dropbox.

Call pickImage() from a View.OnClickListener or onOptionsItemSelected.

    private fun pickImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, PICK_PHOTO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
            try {
                data?.let {
                    val inputStream: InputStream? =
                        context?.contentResolver?.openInputStream(it.data!!)
                    inputStream?.let { stream ->
                        itemViewModel.uploadPicture(stream)
                    }
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            }
        }
    }

    companion object {
        const val PICK_PHOTO = 1
    }

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

#1071 - Specified key was too long; max key length is 767 bytes

run this query before your query:

SET @@global.innodb_large_prefix = 1;

this will increase limit to 3072 bytes.

How to run DOS/CMD/Command Prompt commands from VB.NET?

Imports System.IO
Public Class Form1
    Public line, counter As String
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        counter += 1
        If TextBox1.Text = "" Then
            MsgBox("Enter a DNS address to ping")
        Else
            'line = ":start" + vbNewLine
            'line += "ping " + TextBox1.Text
            'MsgBox(line)
            Dim StreamToWrite As StreamWriter
            StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
            StreamToWrite.Write(":start" + vbNewLine + _
                                "Ping -t " + TextBox1.Text)
            StreamToWrite.Close()
            Dim p As New System.Diagnostics.Process()
            p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
            p.Start()
        End If
    End Sub
End Class

This works as well

What is the best way to use a HashMap in C++?

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

What is an idiomatic way of representing enums in Go?

For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T} would get marshaled to ["adenine","cytosine","guanine","thymine"].

type Base string

const (
    A Base = "adenine"
    C      = "cytosine"
    G      = "guanine"
    T      = "thymine"
)

When using iota, the values get marshaled into integers. In the following example, []Base{A,C,G,T} would get marshaled to [0,1,2,3].

type Base int

const (
    A Base = iota
    C
    G
    T
)

Here's an example comparing both approaches:

https://play.golang.org/p/VvkcWvv-Tvj

Generate SHA hash in C++ using OpenSSL library

OpenSSL has a horrible documentation with no code examples, but here you are:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

Usage:

unsigned char md[SHA256_DIGEST_LENGTH]; // 32 bytes
if(!simpleSHA256(<data buffer>, <data length>, md))
{
    // handle error
}

Afterwards, md will contain the binary SHA-256 message digest. Similar code can be used for the other SHA family members, just replace "256" in the code.

If you have larger data, you of course should feed data chunks as they arrive (multiple SHA256_Update calls).

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

iOS UIImagePickerController result image orientation after upload

Here's UIImage extension for swift:

extension UIImage {

    func fixOrientation() -> UIImage {

        // No-op if the orientation is already correct
        if ( self.imageOrientation == UIImageOrientation.Up ) {
            return self;
        }

        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform: CGAffineTransform = CGAffineTransformIdentity

        if ( self.imageOrientation == UIImageOrientation.Down || self.imageOrientation == UIImageOrientation.DownMirrored ) {
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
        }

        if ( self.imageOrientation == UIImageOrientation.Left || self.imageOrientation == UIImageOrientation.LeftMirrored ) {
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
        }

        if ( self.imageOrientation == UIImageOrientation.Right || self.imageOrientation == UIImageOrientation.RightMirrored ) {
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform,  CGFloat(-M_PI_2));
        }

        if ( self.imageOrientation == UIImageOrientation.UpMirrored || self.imageOrientation == UIImageOrientation.DownMirrored ) {
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformScale(transform, -1, 1)
        }

        if ( self.imageOrientation == UIImageOrientation.LeftMirrored || self.imageOrientation == UIImageOrientation.RightMirrored ) {
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
        }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        var ctx: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
            CGImageGetBitsPerComponent(self.CGImage), 0,
            CGImageGetColorSpace(self.CGImage),
            CGImageGetBitmapInfo(self.CGImage));

        CGContextConcatCTM(ctx, transform)

        if ( self.imageOrientation == UIImageOrientation.Left ||
            self.imageOrientation == UIImageOrientation.LeftMirrored ||
            self.imageOrientation == UIImageOrientation.Right ||
            self.imageOrientation == UIImageOrientation.RightMirrored ) {
                CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)
        } else {
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
        }

        // And now we just create a new UIImage from the drawing context and return it
        return UIImage(CGImage: CGBitmapContextCreateImage(ctx))!
    }
}

Based on MetalHeart2003's earlier work..

Center a H1 tag inside a DIV

On the hX tag

width: 100px;
margin-left: auto;
margin-right: auto;

Should I use string.isEmpty() or "".equals(string)?

You can use apache commons StringUtils isEmpty() or isNotEmpty().

Check if boolean is true?

It depends on your situation.

I would say, if your bool has a good name, then:

if (control.IsEnabled)  // Read "If control is enabled."
{
}

would be preferred.

If, however, the variable has a not-so-obvious name, checking against true would be helpful in understanding the logic.

if (first == true)  // Read "If first is true."
{
}

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

What is the purpose of the "final" keyword in C++11 for functions?

Final keyword in C++ when added to a function, prevents it from being overridden by a base class. Also when added to a class prevents inheritance of any type. Consider the following example which shows use of final specifier. This program fails in compilation.

#include <iostream>
using namespace std;

class Base
{
  public:
  virtual void myfun() final
  {
    cout << "myfun() in Base";
  }
};
class Derived : public Base
{
  void myfun()
  {
    cout << "myfun() in Derived\n";
  }
};

int main()
{
  Derived d;
  Base &b = d;
  b.myfun();
  return 0;
}

Also:

#include <iostream>
class Base final
{
};

class Derived : public Base
{
};

int main()
{
  Derived d;
  return 0;
}

What and When to use Tuple?

This is the most important thing to know about the Tuple type. Tuple is a class, not a struct. It thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection.

Note: The properties Item1, Item2, and further do not have setters. You cannot assign them. The Tuple is immutable once created in memory.

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

What are the most useful Intellij IDEA keyboard shortcuts?

These are some of my most used keyboard short cuts

Syntax aware selection in the editor selects a word at the caret and then selects expanding areas of the source code. For example, it may select a method name, then the expression that calls this method, then the whole statement, then the containing block, etc.: Ctrl+W

Basic Code Completion, to complete methods, keywords etc.: Ctrl+Space

Go to Declaration. Use this to navigate to the declaration of a class, method or variable used somewhere in the code: Ctrl+B

Introduce Variable Refactoring, to create a variable from an expression. This expression may even be incomplete or contain errors. Since version 8, IDEA intelligently selects a likely expression when no text is selected: Ctrl+Alt+V

Go to Class, to quickly open any class in the editor: Ctrl+N

To open any file, not just classes: Ctrl+Shift+N

Comment/Uncomment current line or selection: Ctrl+/ and Ctrl+Shift+/

Quick JavaDoc Popup to show the JavaDoc of the method or class at the text cursor: Ctrl+Q (Ctrl+J on Mac OS X)

Smart Type Completion to complete an expression with a method call or variable with a type suitable in the current Context: Ctrl+Shift+Space

Rename refactoring to rename any identifier. Can look in comments, text files and across different languages too: Shift+F6

Select in Popup to quickly select the currently edited element (class, file, method or field) in any view (Project View, Structure View or other): Alt+F1

Highlight Usages in File. Position the text cursor on any identifier without selecting any text and it will show all places in the file where that variable, method etc. is used. Use it on a throws, try or catch keyword to show all places where the exception is thrown. Use it on the implements keyword to highlight the methods of the implemented interface: Ctrl+Shift+F7

Minimum 6 characters regex expression

If I understand correctly, you need a regex statement that checks for at least 6 characters (letters & numbers)?

/[0-9a-zA-Z]{6,}/

Why should I prefer to use member initialization lists?

Before the body of the constructor is run, all of the constructors for its parent class and then for its fields are invoked. By default, the no-argument constructors are invoked. Initialization lists allow you to choose which constructor is called and what arguments that constructor receives.

If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

Call an overridden method from super class in typescript

The key is calling the parent's method using super.methodName();

class A {
    // A protected method
    protected doStuff()
    {
        alert("Called from A");
    }

    // Expose the protected method as a public function
    public callDoStuff()
    {
        this.doStuff();
    }
}

class B extends A {

    // Override the protected method
    protected doStuff()
    {
        // If we want we can still explicitly call the initial method
        super.doStuff();
        alert("Called from B");
    }
}

var a = new A();
a.callDoStuff(); // Will only alert "Called from A"

var b = new B()
b.callDoStuff(); // Will alert "Called from A" then "Called from B"

Try it here

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

Selenium WebDriver findElement(By.xpath()) not working for me

You can use contains too:

element = findElement(By.xpath("//input[contains (@test-id,"test-username")]");

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

Sharing a variable between multiple different threads

You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".

Please refer the below the code :

public class EvenOdd {

    static int a = 0;

    public static void main(String[] args) {

        EvenOdd eo = new EvenOdd();

        A aobj = eo.new A();
        B bobj = eo.new B();

        aobj.a = Lock.lock1;
        aobj.b = Lock.lock2;

        bobj.a = Lock.lock2;
        bobj.b = Lock.lock1;

        Thread t1 = new Thread(aobj);
        Thread t2 = new Thread(bobj);

        t1.start();
        t2.start();
    }

    static class Lock {
        final static Object lock1 = new Object();
        final static Object lock2 = new Object();
    }

    class A implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {
                try {
                    System.out.println(++EvenOdd.a + " A ");
                    synchronized (a) {
                        a.notify();
                    }
                    synchronized (b) {
                        b.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class B implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {

                try {
                    synchronized (b) {
                        b.wait();
                        System.out.println(++EvenOdd.a + " B ");
                    }
                    synchronized (a) {
                        a.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

OUTPUT :

1 A 
2 B 
3 A 
4 B 
5 A 
6 B 
7 A 
8 B 
9 A 
10 B 

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

How to replace a character with a newline in Emacs?

M-x replace-string RET ; RET C-q C-j.

  • C-q for quoted-insert,

  • C-j is a newline.

Cheers!

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Is there a way that I can check if a data attribute exists?

I needed a simple boolean to work with. Because it's undefined of not present, and not false, I use the !! to convert to boolean:

var hasTimer = !!$("#dataTable").data('timer');
if( hasTimer ){ /* ....... */ }

An alternative solution would be using filter:

if( $("#dataTable").filter('[data-timer]').length!==0) { /* ....... */ }

LINQ Aggregate algorithm explained

Everyone has given his explanation. My explanation is like that.

Aggregate method applies a function to each item of a collection. For example, let's have collection { 6, 2, 8, 3 } and the function Add (operator +) it does (((6+2)+8)+3) and returns 19

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: (result, item) => result + item);
// sum: (((6+2)+8)+3) = 19

In this example there is passed named method Add instead of lambda expression.

var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate(func: Add);
// sum: (((6+2)+8)+3) = 19

private static int Add(int x, int y) { return x + y; }

Single vs Double quotes (' vs ")

Quoting Conventions for Web Developers

The Short Answer

In HTML the use of single quotes (') and double quotes (") are interchangeable, there is no difference.

But consistency is recommended, therefore we must pick a syntax convention and use it regularly.

The Long Answer

Web Development often consists of many programming languages. HTML, JS, CSS, PHP, ASP, RoR, Python, ect. Because of this we have many syntax conventions for different programing languages. Often habbits from one language will follow us to other languages, even if it is not considered "proper" i.e. commenting conventions. Quoting conventions also falls into this category for me.

But I tend to use HTML tightly in conjunction with PHP. And in PHP there is a major difference between single quotes and double quotes. In PHP with double quotes "you can insert variables directly within the text of the string". (scriptingok.com) And when using single quotes "the text appears as it is". (scriptingok.com)

PHP takes longer to process double quoted strings. Since the PHP parser has to read the whole string in advance to detect any variable inside—and concatenate it—it takes longer to process than a single quoted string. (scriptingok.com)

 

Single quotes are easier on the server. Since PHP does not need to read the whole string in advance, the server can work faster and happier. (scriptingok.com)

Other things to consider

  1. Frequency of double quotes within string. I find that I need to use double quotes (") within my strings more often than I need to use single quotes (') within strings. To reduce the number of character escapes needed I favor single quote delimiters.
  2. It's easier to make a single quote. This is fairly self explanatory but to clarify, why press the SHIFT key more times then you have to.

My Convention

With this understanding of PHP I have set the convention (for myself and the rest of my company) that strings are to be represented as single quotes by default for server optimization. Double quotes are used within the string if a quotes are required such as JavaScript within an attribute, for example:

<button onClick='func("param");'>Press Me</button>

Of course if we are in PHP and want the parser to handle PHP variables within the string we should intentionally use double quotes. $a='Awesome'; $b = "Not $a";

Sources

Single quotes vs Double quotes in PHP. (n.d.). Retrieved November 26, 2014, from http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

jQuery checkbox event handling

Using the new 'on' method in jQuery (1.7): http://api.jquery.com/on/

    $('#myform').on('change', 'input[type=checkbox]', function(e) {
        console.log(this.name+' '+this.value+' '+this.checked);

    });
  • the event handler will live on
  • will capture if the checkbox was changed by keyboard, not just click

R dplyr: Drop multiple columns

Another way is to mutate the undesired columns to NULL, this avoids the embedded parentheses :

head(iris,2) %>% mutate_at(drop.cols, ~NULL)
#   Petal.Length Petal.Width Species
# 1          1.4         0.2  setosa
# 2          1.4         0.2  setosa

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

How can I replace text with CSS?

Based on mikemaccana’s answer, this worked for me

button {
  position: absolute;
  visibility: hidden;
}

button:before {
  content: "goodbye";
  visibility: visible;
}

§ Absolute positioning

an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements.