Programs & Examples On #Mov

Questions related to the assembler `mov` instruction

PHP array value passes to next row

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

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

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

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

When to create variables (memory management)

So notice variables are on the stack, the values they refer to are on the heap. So having variables is not too bad but yes they do create references to other entities. However in the simple case you describe it's not really any consequence. If it is never read again and within a contained scope, the compiler will probably strip it out before runtime. Even if it didn't the garbage collector will be able to safely remove it after the stack squashes. If you are running into issues where you have too many stack variables, it's usually because you have really deep stacks. The amount of stack space needed per thread is a better place to adjust than to make your code unreadable. The setting to null is also no longer needed

Please help me convert this script to a simple image slider

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

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

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

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

CSS:

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

JavaScript:

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

http://jsfiddle.net/RmF57/

Highlight Anchor Links when user manually scrolls?

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

Removing "http://" from a string

Use look behinds in preg_replace to remove anything before //.

preg_replace('(^[a-z]+:\/\/)', '', $url); 

This will only replace if found in the beginning of the string, and will ignore if found later

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I encountered this because the http2 server closed the connection when sending a big response to the Chrome.

Why? Because it is just a setting of the http2 server, named WriteTimeout.

Server Discovery And Monitoring engine is deprecated

This will work:

// Connect to Mongo
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);

mongoose
  .connect(db) // Connection String here
  .then(() => console.log("MongoDB Connected..."))
  .catch(() => console.log(err));

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

There is a bug about Eclipse and spring-boot-starter-parent 2.1.5

"if the maven packaging attribute is war then no problem.The problem is in jar type." So you can also fix this problem by changing packaging type.

<packaging>war</packaging>

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

Add this comment on the top of your file to disable warning.

/* eslint-disable react-hooks/exhaustive-deps */

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

I'm not exactly sure where my problem was, but I believe it was because I was using the same global packages from both npm and Yarn.

I uninstalled all the npm global packages, then when using yarn commands once again, the problem was gone.

To see global packages installed...

for npm:

npm ls -g --depth=0

for Yarn:

yarn global list

I then uninstalled each package I saw in the npm listing, using:

npm uninstall -g <package-name>

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

For me the error was caused by wrong type hint of url string. I used:

export class TodoService {

  apiUrl: String = 'https://jsonplaceholder.typicode.com/todos' // wrong uppercase String

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

where I should have used

export class TodoService {

  apiUrl: string = 'https://jsonplaceholder.typicode.com/todos' // lowercase string!

  constructor(private httpClient: HttpClient) { }

  getTodos(): Observable<Todo[]> {
    return this.httpClient.get<Todo[]>(this.apiUrl)
  }
}

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

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

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

const handleClick = async (item: NavheadersType, index: number) => {
    const newNavHeaders = [...navheaders];
    if (item.url) {
      await router.push(item.url);   =>>>> line causing error (causing route to happen)
      // router.push(item.url);  =>>> coreect line
      newNavHeaders.forEach((item) => (item.active = false));
      newNavHeaders[index].active = true;
      setnavheaders([...newNavHeaders]);
    }
  };

Set the space between Elements in Row Flutter

There are many ways of doing it, I'm listing a few here:

  1. Use SizedBox if you want to set some specific space

    Row(
      children: <Widget>[
        Text("1"),
        SizedBox(width: 50), // give it width
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Spacer if you want both to be as far apart as possible.

    Row(
      children: <Widget>[
        Text("1"),
        Spacer(), // use Spacer
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use mainAxisAlignment according to your needs:

    Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly, // use whichever suits your need
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give some spacing

    Wrap(
      spacing: 100, // set spacing here
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give it alignment

    Wrap(
      alignment: WrapAlignment.spaceAround, // set your alignment
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

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

In my case

build.gradle(Project)

was

ext.kotlin_version = '1.2.71'

updated to

ext.kotlin_version = '1.3.0'

looks problem has gone for now

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.

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

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

How to scroll page in flutter

Two way to add Scroll in page

1. Using SingleChildScrollView :

     SingleChildScrollView(
          child: Column(
            children: [
              Container(....),
              SizedBox(...),
              Container(...),
              Text(....)
            ],
          ),
      ),

2. Using ListView : ListView is default provide Scroll no need to add extra widget for scrolling

     ListView(
          children: [
            Container(..),
            SizedBox(..),
            Container(...),
            Text(..)
          ],
      ),

Under which circumstances textAlign property works in Flutter?

textAlign property only works when there is a more space left for the Text's content. Below are 2 examples which shows when textAlign has impact and when not.


No impact

For instance, in this example, it won't have any impact because there is no extra space for the content of the Text.

Text(
  "Hello",
  textAlign: TextAlign.end, // no impact
),

enter image description here


Has impact

If you wrap it in a Container and provide extra width such that it has more extra space.

Container(
  width: 200,
  color: Colors.orange,
  child: Text(
    "Hello",
    textAlign: TextAlign.end, // has impact
  ),
)

enter image description here

How to format DateTime in Flutter , How to get current time in flutter?

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

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

Rounded Corners Image in Flutter

Use ClipRRect it will work perfectly

ClipRRect(
    borderRadius: BorderRadius.circular(8.0),
    child: Image.network(
        subject['images']['large'],
        height: 150.0,
        width: 100.0,
    ),
)

Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

_x000D_
_x000D_
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
 _x000D_
 console.log(array);
_x000D_
_x000D_
_x000D_

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

There is nothing to change. Pass only in the connect function {useNewUrlParser: true }.

This will work:

    MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
        if(err) {
            console.log(err);
        }
        else {
            console.log('connected to ' + url);
            db.close();
        }
    })

How to remove package using Angular CLI?

You can use npm uninstall <package-name> will remove it from your package.json file and from node_modules.

If you do ng help command, you will see that there is no ng remove/delete supported command. So, basically you cannot revert the ng add behavior yet.

Angular 6 Material mat-select change method removed

For me (selectionChange) and the suggested (onSelectionChange) didn't work and I'm not using ReactiveForms. What I ended up doing was using the (valueChange) event like:

<mat-select (valueChange)="someFunction()">

And this worked for me

Dart: mapping a list (list.map)

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) { return Tab(text: title)}).toList()
      ,
    ),

pip: no module named _internal

This solution works for me:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall

or use sudo for elevated permissions (sudo python3 get-pip.py --force-reinstall).

Of course, you can also use python instead of python3 ;)

Source

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

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I've come across the same issue after adding the following dependency:

implementation 'com.evernote:android-state:1.4.1'
annotationProcessor 'com.evernote:android-state-processor:1.4.1'

And the reason was that latest version of evernote uses dependencies to AndroidX, while I had support library version 27.1.1 in my project. So there was an option of upgrading support libraries to 28.0.0, as the other answers suggest, but that was a bit tricky for a large project with lots of custom views. So, I resolved the issue by downgrading evernote version to 1.3.1.

How to remove whitespace from a string in typescript?

The trim() method removes whitespace from both sides of a string.

To remove all the spaces from the string use .replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();

Removing Conda environment

You may try the following: Open anaconda command prompt and type

conda remove --name myenv --all

This will remove the entire environment.

Further reading: docs.conda.io > Manage Environments

Flutter: how to make a TextField with HintText but no Underline?

decoration: InputDecoration(
 border:OutLineInputBorder(
 borderSide:BorderSide.none
 bordeRadius: BordeRadius.circular(20.0)
 )
)

Want to upgrade project from Angular v5 to Angular v6

There are few steps to upgrade 2/4/5 to Angular 6.

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix the issue related to "angular.json" :-

ng update @angular/cli --migrate-only --from=1.7.4

Store MIGRATION
https://github.com/ngrx/platform/blob/master/MIGRATION.md#ngrxstore

RXJS MIGRATION
https://www.academind.com/learn/javascript/rxjs-6-what-changed/

Hoping this will help you :)

How to remove the Flutter debug banner?

The debug banner appears only while in development and is automatically removed in the release build.

To hide this there is a need to set debugShowCheckedModeBanner to false

MaterialApp(
  debugShowCheckedModeBanner: false,
)

enter image description here

How to view instagram profile picture in full-size?

replace "150x150" with 720x720 and remove /vp/ from the link.it should work.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

What would be wrong with doing;

<div className="" key={index}>
   {i.title}
</div>

[/*Use IIFE */]

{(function () {
     if (child.children && child.children.length !== 0) {
     let menu = createMenu(child.children);
     console.log("nested menu", menu);
     return menu;
   }
 })()}

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

Spring Security Documentation mentions the reason for blocking // in the request.

For example, it could contain path-traversal sequences (like /../) or multiple forward slashes (//) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don’t. To protect against issues like these, FilterChainProxy uses an HttpFirewall strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes.

So there are two possible solutions -

  1. remove double slash (preferred approach)
  2. Allow // in Spring Security by customizing the StrictHttpFirewall using the below code.

Step 1 Create custom firewall that allows slash in URL.

@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    StrictHttpFirewall firewall = new StrictHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);    
    return firewall;
}

Step 2 And then configure this bean in websecurity

@Override
public void configure(WebSecurity web) throws Exception {
    //@formatter:off
    super.configure(web);
    web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
....
}

Step 2 is an optional step, Spring Boot just needs a bean to be declared of type HttpFirewall and it will auto-configure it in filter chain.

Spring Security 5.4 Update

In Spring security 5.4 and above (Spring Boot >= 2.4.0), we can get rid of too many logs complaining about the request rejected by creating the below bean.

import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.firewall.HttpStatusRequestRejectedHandler;

@Bean
RequestRejectedHandler requestRejectedHandler() {
   return new HttpStatusRequestRejectedHandler();
}

ReferenceError: fetch is not defined

Node.js hasn't implemented the fetch() method, but you can use one of the external modules of this fantastic execution environment for JavaScript.

In one of the answers above, "node-fetch" is cited and that's a good choice.

In your project folder (the directory where you have the .js scripts) install that module with the command:

npm i node-fetch --save

Then use it as a constant in the script you want to execute with Node.js, something like this:

const fetch = require("node-fetch");

Issue in installing php7.2-mcrypt

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

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

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

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

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

This is also possible using a series of self-overwriting getters:

(This is similar to jontro's solution, but doesn't require a counter variable.)

_x000D_
_x000D_
(() => {_x000D_
    "use strict";_x000D_
    Object.defineProperty(this, "a", {_x000D_
        "get": () => {_x000D_
            Object.defineProperty(this, "a", {_x000D_
                "get": () => {_x000D_
                    Object.defineProperty(this, "a", {_x000D_
                        "get": () => {_x000D_
                            return 3;_x000D_
                        }_x000D_
                    });_x000D_
                    return 2;_x000D_
                },_x000D_
                configurable: true_x000D_
            });_x000D_
            return 1;_x000D_
        },_x000D_
        configurable: true_x000D_
    });_x000D_
    if (a == 1 && a == 2 && a == 3) {_x000D_
        document.body.append("Yes, it’s possible.");_x000D_
    }_x000D_
})();
_x000D_
_x000D_
_x000D_

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

Import functions from another js file. Javascript

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

models/course.js

export function Course() {
    this.id = '';
    this.name = '';
};

models/student.js

import { Course } from './course.js';

export function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
};

index.html

<div id="myDiv">
</div>
<script type="module">
    import { Student } from './models/student.js';

    window.onload = function () {
        var x = new Student();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

in the manifest file set second activity parentActivityName as first activity and remove the screenOrientation parameter to the second activity. it means your first activity is the parent and decide to an orientation of your second activity.

<activity
        android:name=".view.FirstActiviy"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme" />

<activity
        android:name=".view.SecondActivity"
        android:parentActivityName=".view.FirstActiviy"
        android:theme="@style/AppTheme.Transparent" />

How to shift a block of code left/right by one space in VSCode?

UPDATE

While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.

This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.

The type WebMvcConfigurerAdapter is deprecated

Since Spring 5 you just need to implement the interface WebMvcConfigurer:

public class MvcConfig implements WebMvcConfigurer {

This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter class

See here:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.html

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

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

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

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

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

Settings->Additional Settings->Developer Options

1) Turn ON Developer Options
2) Turn ON USB Debugging
3) Turn OFF MIUI optimization
4) Turn ON Install via USB

No provider for HttpClient

You are getting error for HttpClient so, you are missing HttpClientModule for that.

You should import it in app.module.ts file like this -

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

and mention it in the NgModule Decorator like this -

@NgModule({
...
imports:[ HttpClientModule ]
...
})

If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.

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

just clean and make project / rebuilt fixed my issue give a try :-)

How to remove an unpushed outgoing commit in Visual Studio?

Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made. In order to reset before a given commit you thus have to select its parent.

Depending on what you want to do with the changes choose hard, which will get rid of them locally. Or choose soft which will undo the commit but will leave your working directory with the changes in your discarded commit.

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

I simply ran composer update and it resolved my issue - Laravel 6.*

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

I'm using, Angular CLI: 8.1.2 Node: 12.14.1 OS: win32 x64

Strangely, this helped me

npm cache clean --force
npm uninstall @angular/cli
npm install @angular/[email protected]

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

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

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

Removing the JUnit library, and then adding it again fixed this issue for me.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

This is due to the interfering messages that come on to the page. There are multiple frames on the page which communicate with the page using window message event and object. few of them can be third party services like cookieq for managing cookies, or may be cartwire an e-com integration service.

You need to handle the onmessage event to check from where the messages are coming, and then parse the JSON accordingly.

I faced a similar problem, where one of the integration was passing a JSON object and other was passing a string starting with u

how to remove json object key and value.?

Follow this, it can be like what you are looking:

_x000D_
_x000D_
var obj = {_x000D_
    Objone: 'one',_x000D_
    Objtwo: 'two'_x000D_
};_x000D_
_x000D_
var key = "Objone";_x000D_
delete obj[key];_x000D_
console.log(obj); // prints { "objtwo": two}
_x000D_
_x000D_
_x000D_

How to use switch statement inside a React component?

Here is a full working example using a button to switch between components

you can set a constructor as following

constructor(props)
{
    super(props);
    this.state={
        currentView: ''
    }
}

then you can render components as following

  render() 
{
    const switchView = () => {

    switch(this.state.currentView) 
    {

      case "settings":   return <h2>settings</h2>;
      case "dashboard":   return <h2>dashboard</h2>;

      default:      return <h2>dashboard</h2>
    }
  }

    return (

       <div>

            <button onClick={(e) => this.setState({currentView: "settings"})}>settings</button>
            <button onClick={(e) => this.setState({currentView: "dashboard"})}>dashboard</button>

            <div className="container">
                { switchView() }
            </div>


        </div>
    );
}

}

As you can see I am using a button to switch between states.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

You can delete all the documents from a collection in MongoDB, you can use the following:

db.users.remove({})

Alternatively, you could use the following method as well:

db.users.deleteMany({})

Follow the following MongoDB documentation, for further details.

To remove all documents from a collection, pass an empty filter document {} to either the db.collection.deleteMany() or the db.collection.remove() method.

How to view Plugin Manager in Notepad++

I changed the plugin folder name. Restart Notepad ++ It works now, a

Android 8: Cleartext HTTP traffic not permitted

While the working answer, for me, was this by @PabloCegarra:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

You may receive a security warning regarding the cleartextTrafficPermitted="true"

If you know the domains to 'white list' you should mix both accepted answer and the above one:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">books.google.com</domain>
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </domain-config>
</network-security-config>

This code is working for me, but my app needs to retrieve data from books.google.com only. By this way the security warning disappears.

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Is there way to use two PHP versions in XAMPP?

Maybe a bit late, but I am using a batch to rename the PHP folders (a slightly modified version of the phpswitch I found years ago).

You copy the different folders into your XAMPP installation. Each PHP folder (except for the active one) receives the version number as a suffix (eg. php_5.6.32). In ALL PHP folders, a file (PHP_VERSION) is created, which contains only the respective version number, so the Script can grab this information. But that's all described in the README.

Since PHP7 the httpd-xampp.conf loads the php7ts.dll instead of the php5ts.dll. So i had to extend the script (PHPSwitch.php) to rename these config-files too by following the same approach.

    $renameCur = new PHPSwitch_Rename($currInst['path'], $this->_cfg['phpInstallationsPath'] . $this->_cfg['phpDirName'] . '_' . $currInst['version']);
    $renameNew = new PHPSwitch_Rename($newInst['path'], $this->_cfg['phpInstallationsPath'] . $this->_cfg['phpDirName']);

    $apache_curent      = $this->_cfg["phpInstallationsPath"]."apache/conf/extra/httpd-xampp.conf";
    $apache_curent_rename   = $this->_cfg["phpInstallationsPath"]."apache/conf/extra/httpd-xampp_".$currInst['version'].".conf";
    $apache_new             = $this->_cfg["phpInstallationsPath"]."apache/conf/extra/httpd-xampp_".$newInst['version'].".conf";
    $apache_new_rename      = $this->_cfg["phpInstallationsPath"]."apache/conf/extra/httpd-xampp.conf";

    $renameCur_apache_conf = new PHPSwitch_Rename($apache_curent, $apache_curent_rename);
    $renameNew_apache_conf = new PHPSwitch_Rename($apache_new, $apache_new_rename);

    $transaction = new PHPSwitch_Rename_Transaction();
    $transaction->add($renameCur);
    $transaction->add($renameNew);
    $transaction->add($renameCur_apache_conf);
    $transaction->add($renameNew_apache_conf);

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Widget _bottom() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Expanded(
          child: Container(
            color: Colors.amberAccent,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: new List<int>.generate(50, (index) => index + 1)
                    .map((item) {
                  return Text(
                    item.toString(),
                    style: TextStyle(fontSize: 20),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
        Container(
          color: Colors.blue,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'BoTToM',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 33),
              ),
            ],
          ),
        ),
      ],
    );
  }

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

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

flutter remove back button on appbar

Just Make it transparent, and no action while pressend

AppBar(
            leading: IconButton(
              icon: Icon(
                Icons.arrow_back,
                color: Colors.white.withOpacity(0),
              ),
              onPressed: () {},
            ),

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

Angular 4 Pipe Filter

The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

export class FilterPipe implements PipeTransform {
    transform(items: any[], filterBy: string): any {
        return items.filter(item => item.id.indexOf(filterBy) !== -1);
    }
}

And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

export class ProductFilterPipe implements PipeTransform {

    transform(value: IProduct[], filterBy: string): IProduct[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
    }
}

And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

How to remove docker completely from ubuntu 14.04

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update

How to completely uninstall kubernetes

kubeadm reset 
/*On Debian base Operating systems you can use the following command.*/
# on debian base 
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube* 


/*On CentOs distribution systems you can use the following command.*/
#on centos base
sudo yum remove kubeadm kubectl kubelet kubernetes-cni kube*


# on debian base
sudo apt-get autoremove

#on centos base
sudo yum autoremove

/For all/
sudo rm -rf ~/.kube

How to completely uninstall python 2.7.13 on Ubuntu 16.04

caution : It is not recommended to remove the default Python from Ubuntu, it may cause GDM(Graphical Display Manager, that provide graphical login capabilities) failed.

To completely uninstall Python2.x.x and everything depends on it. use this command:

sudo apt purge python2.x-minimal

As there are still a lot of packages that depend on Python2.x.x. So you should have a close look at the packages that apt wants to remove before you let it proceed.

Thanks, I hope it will be helpful for you.

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

Show/hide widgets in Flutter programmatically

For beginner try this too.

class Visibility extends StatefulWidget {
  @override
  _VisibilityState createState() => _VisibilityState();
}

class _VisibilityState extends State<Visibility> {
  bool a = true;
  String mText = "Press to hide";

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Visibility",
      home: new Scaffold(
          body: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new RaisedButton(
                onPressed: _visibilitymethod, child: new Text(mText),),
                a == true ? new Container(
                width: 300.0,
                height: 300.0,
                color: Colors.red,
              ) : new Container(),
            ],
          )
      ),
    );
  }

  void _visibilitymethod() {
    setState(() {
      if (a) {
        a = false;
        mText = "Press to show";
      } else {
        a = true;
        mText = "Press to hide";
      }
    });
  }
}

Get Path from another app (WhatsApp)

Using the code example below will return to you the bitmap :

BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))

After that you all know what you have to do.

How to specify legend position in matplotlib in graph coordinates

The loc parameter specifies in which corner of the bounding box the legend is placed. The default for loc is loc="best" which gives unpredictable results when the bbox_to_anchor argument is used.
Therefore, when specifying bbox_to_anchor, always specify loc as well.

The default for bbox_to_anchor is (0,0,1,1), which is a bounding box over the complete axes. If a different bounding box is specified, is is usually sufficient to use the first two values, which give (x0, y0) of the bounding box.

Below is an example where the bounding box is set to position (0.6,0.5) (green dot) and different loc parameters are tested. Because the legend extents outside the bounding box, the loc parameter may be interpreted as "which corner of the legend shall be placed at position given by the 2-tuple bbox_to_anchor argument".

enter image description here

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6, 3
fig, axes = plt.subplots(ncols=3)
locs = ["upper left", "lower left", "center right"]
for l, ax in zip(locs, axes.flatten()):
    ax.set_title(l)
    ax.plot([1,2,3],[2,3,1], "b-", label="blue")
    ax.plot([1,2,3],[1,2,1], "r-", label="red")
    ax.legend(loc=l, bbox_to_anchor=(0.6,0.5))
    ax.scatter((0.6),(0.5), s=81, c="limegreen", transform=ax.transAxes)

plt.tight_layout()    
plt.show()

See especially this answer for a detailed explanation and the question What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? .


If you want to specify the legend position in other coordinates than axes coordinates, you can do so by using the bbox_transform argument. If may make sense to use figure coordinates

ax.legend(bbox_to_anchor=(1,0), loc="lower right",  bbox_transform=fig.transFigure)

It may not make too much sense to use data coordinates, but since you asked for it this would be done via bbox_transform=ax.transData.

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

I had a similar problem after updating my VS2017. Project built fine; but lots of 'errors' when code was brought up in the editor. Even tried reinstalling VS. I was able to solve it by setting the option “Ignore Standard Include Paths” to Yes. Attempted to build the solution with lots of errors. Went back and set the option to No. After rebuilding, my problem went away.

How do you fix the "element not interactable" exception?

It will be better to use xpath

from selenium import webdriver
driver.get('www.example.com')
button = driver.find_element_by_xpath('xpath')
button.click()

VirtualBox Cannot register the hard disk already exists

It's possible to change the UUID on the VDI file using the command:

 VBoxManage internalcommands sethduuid <file.vdi>

It seems this command assigns a new "random" UUID to the file. No much documentation on it, though.

The create-react-app imports restriction outside of src directory

If you only need to import a single file, such as README.md or package.json, then this can be explicitly added to ModuleScopePlugin()

config/paths.js

const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
module.exports = {
  appPackageJson: resolveApp('package.json'),
  appReadmeMD:    resolveApp('README.md'),
};

config/webpack.config.dev.js + config/webpack.config.prod.js

module.exports = {
  resolve: {
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [
          paths.appPackageJson,
          paths.appReadmeMD         // README.md lives outside of ./src/ so needs to be explicitly included in ModuleScopePlugin()
      ]),
    ]
  }
}

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

If you are using foreignkey then you have to use "on_delete=models.CASCADE" as it will eliminate the complexity developed after deleting the original element from the parent table. As simple as that.

categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE)

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

I had the same problem. If you are checking out any github project, then instead of using git clone, use git lfs clone, as sometimes, some large files are not properly cloned by using git only. Also, make sure your bitcode is disabled.

Angular: How to update queryParams without changing route

First, we need to import the router module from angular router and declare its alias name

import { Router } from '@angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
    private router: Router ---> decalre alias name
  ) { }
}

1. You can change query params by using "router.navigate" function and pass the query parameters

this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
});

It will update query params in the current i.e activated route

  1. The below will redirect to abc page with _id, day and name as query params

    this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name: "dfd"} });

    It will update query params in the "abc" route along with three query paramters

For fetching query params:-

    import { ActivatedRoute } from '@angular/router'; //import activated routed

    export class ABC implements OnInit {

    constructor(
        private route: ActivatedRoute //declare its alias name
      ) {}

    ngOnInit(){
       console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
    }

Component is part of the declaration of 2 modules

As the error says to remove the module AddEvent from root if your Page/Component is already had ionic module file if not just remove it from the other/child page/component, at the end page/component should be present in only one module file imported if to be used.

Specifically, you should add in root module if required in multiple pages and if in specific pages keep it in only one page.

HTML5 Video autoplay on iPhone

Does playsinline attribute help?

Here's what I have:

<video autoplay loop muted playsinline class="video-background ">
  <source src="videos/intro-video3.mp4" type="video/mp4">
</video>

See the comment on playsinline here: https://webkit.org/blog/6784/new-video-policies-for-ios/

onKeyDown event not working on divs in React

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

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

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

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

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

How to Install Font Awesome in Laravel Mix

Try in your webpack.mix.js to add the '*'

.copy('node_modules/font-awesome/fonts/*', 'public/fonts')

Angular 2 Cannot find control with unspecified name attribute on formArrays

In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

Visual Studio Code open tab in new window

If you are using the excellent

VSCode for Mac, 2020

simply tap Apple-Shift-N (as in "new window")

Drag whatever you want there.

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for linux and specifically Ubuntu 20:04. First ensure you have Java installed before proceeding:

1. java -version
2. sudo apt-get update
3. sudo apt-get install openjdk-8-jdk

Open .bashrc

vim $HOME/.bashrc 

Set Java environment variables.

export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export JRE_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre"

Visit Gradle's website and identify the version you would like to install. Replace version 6.5.1 with the version number you would like to install.

 1. sudo apt-get update
 2. cd /tmp && curl -L -O https://services.gradle.org/distributions/gradle-6.5.1-bin.zip
 3. sudo mkdir /opt/gradle
 4. sudo unzip -d /opt/gradle /tmp/gradle-6.5.1-bin.zip

To setup Gradle's environment variables use nano or vim or gedit editors to create a new file:

sudo vim /etc/profile.d/gradle.sh

Add the following lines to gradle.sh

export GRADLE_HOME="/opt/gradle/gradle-6.5.1/"
export PATH=${GRADLE_HOME}/bin:${PATH}

Run the following commands to make gradle.sh executable and to update your bash terminal with the environment variables you set as well as check the installed version.

1. sudo chmod +x /etc/profile.d/gradle.sh
3. source /etc/profile.d/gradle.sh
4. gradle -v

Trying to use fetch and pass in mode: no-cors

Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

The usage is straight pretty forward:
1. Install the package: npm install -g local-ssl-proxy
2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

What is the role of "Flatten" in Keras?

If you read the Keras documentation entry for Dense, you will see that this call:

Dense(16, input_shape=(5,3))

would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')

EDIT: As some people struggled to understand - here you have an explaining image:

enter image description here

Android - how to make a scrollable constraintlayout?

you need surrounded my constraint-layout with a ScrollView tag and gave it the property android:isScrollContainer="true".

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

Attach Authorization header for all axios requests

Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.

export default () => {
    axios.interceptors.request.use(function (requestConfig) {
        if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
            const token = localStorage.token;
            requestConfig.headers['Authorization'] = `Bearer ${token}`;
        }

        return requestConfig;
    }, function (error) {
        return Promise.reject(error);
    });

}

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

You're using splice in a wrong way.

The overloads are:

array.splice(start)

array.splice(start, deleteCount)

array.splice(start, deleteCount, itemForInsertAfterDeletion1, itemForInsertAfterDeletion2, ...)

Start means the index that you want to start, not the element you want to remove. And you should pass the second parameter deleteCount as 1, which means: "I want to delete 1 element starting at the index {start}".

So you better go with:

deleteEvent: function(event) {
  this.events.splice(this.events.indexOf(event), 1);
}

Also, you're using a parameter, so you access it directly, not with this.event.

But in this way you will look up unnecessary for the indexOf in every delete, for solving this you can define the index variable at your v-for, and then pass it instead of the event object.

That is:

v-for="(event, index) in events"
...

<button ... @click="deleteEvent(index)"

And:

deleteEvent: function(index) {
  this.events.splice(index, 1);
}

How to post a file from a form with Axios

This works for me, I hope helps to someone.

var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
    .then(res => {
        console.log({res});
    }).catch(err => {
        console.error({err});
    });

Failed to execute removeChild on Node

Your myCoolDiv element isn't a child of the player container. It's a child of the div you created as a wrapper for it (markerDiv in the first part of the code). Which is why it fails, removeChild only removes children, not descendants.

You'd want to remove that wrapper div, or not add it at all.

Here's the "not adding it at all" option:

_x000D_
_x000D_
var markerDiv = document.createElement("div");_x000D_
markerDiv.innerHTML = "<div id='MyCoolDiv' style='color: #2b0808'>123</div>";_x000D_
document.getElementById("playerContainer").appendChild(markerDiv.firstChild);_x000D_
// -------------------------------------------------------------^^^^^^^^^^^_x000D_
_x000D_
setTimeout(function(){ _x000D_
    var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

Or without using the wrapper (although it's quite handy for parsing that HTML):

_x000D_
_x000D_
var myCoolDiv = document.createElement("div");_x000D_
// Don't reall need this: myCoolDiv.id = "MyCoolDiv";_x000D_
myCoolDiv.style.color = "#2b0808";_x000D_
myCoolDiv.appendChild(_x000D_
  document.createTextNode("123")_x000D_
);_x000D_
document.getElementById("playerContainer").appendChild(myCoolDiv);_x000D_
_x000D_
setTimeout(function(){ _x000D_
    // No need for this, we already have it from the above:_x000D_
    // var myCoolDiv = document.getElementById("MyCoolDiv");_x000D_
    document.getElementById("playerContainer").removeChild(myCoolDiv);_x000D_
}, 1500);
_x000D_
<div id="playerContainer"></div>
_x000D_
_x000D_
_x000D_

How to resolve Unneccessary Stubbing exception

If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

VueJS conditionally add an attribute for an element

Try:

<input :required="test ? true : false">

How to load image (and other assets) in Angular an project?

It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).

Example A:

src
|__assests
   |__images
      |__myimage.png
|__yourmodule
   |__yourpage.html

As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:

<img class="img-responsive" src="../assests/images/myimage.png">

Example B:

src
|__assests
   |__images
      |__myimage.png
|__yourmodule
   |__yoursubmodule
      |__yourpage.html

Here you have to go u in the tree by 2 folders:

<img class="img-responsive" src="../../assests/images/myimage.png">

laravel 5.4 upload image

A good logic for your application could be something like:

 public function uploadGalery(Request $request){
      $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
      ]);
      if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = time().'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/storage/galeryImages/');
        $image->move($destinationPath, $name);
        $this->save();
        return back()->with('success','Image Upload successfully');
      }

    }

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

eslint: error Parsing error: The keyword 'const' is reserved

you also can add this inline instead of config, just add it to the same file before you add your own disable stuff

/* eslint-env es6 */
/* eslint-disable no-console */

my case was disable a file and eslint-disable were not working for me alone

/* eslint-env es6 */
/* eslint-disable */

remove kernel on jupyter notebook

jupyter kernelspec remove now exists, see #7934.

So you can just.

# List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
# Remove it
jupyter kernelspec remove <kernel_name>

That's it.

How to define an optional field in protobuf 3

In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.

If you need a "null" state (and there is no out-of-range value that you can use for this) then you will instead need to encode this as a separate field. For instance, you could do:

message Foo {
  bool has_baz = 1;  // always set this to "true" when using baz
  int32 baz = 2;
}

Alternatively, you could use oneof:

message Foo {
  oneof baz {
    bool baz_null = 1;  // always set this to "true" when null
    int32 baz_value = 2;
  }
}

The oneof version is more explicit and more efficient on the wire but requires understanding how oneof values work.

Finally, another perfectly reasonable option is to stick with proto2. Proto2 is not deprecated, and in fact many projects (including inside Google) very much depend on proto2 features which are removed in proto3, hence they will likely never switch. So, it's safe to keep using it for the foreseeable future.

Flask - Calling python function on button OnClick event

It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.

I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.

With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:

from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/forward/", methods=['POST'])
def move_forward():
    #Moving forward code
    forward_message = "Moving Forward..."
    return render_template('index.html', forward_message=forward_message);

Then in your html, use this:

<form action="/forward/" method="post">
    <button name="forwardBtn" type="submit">Forward</button>
</form>

...To execute your moving forward code. And include this:

{{ forward_message }} 

... where you want the moving forward message to appear on your template.

This will cause your page to reload, which is inevitable without using AJAX and Javascript.

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

Google API authentication: Not valid origin for the client

Trying on a different browser(chrome) worked for me and clearing cache on firefox cleared the issue.

(PS: Not add the hosting URIs to Authorized JavaScript origins in API credentials would give you Error:redirect_uri_mismatch)

How can I regenerate ios folder in React Native project?

  1. Open Terminal/cmd
  2. Move to the folder/directory where the project "ProjectName" folder exist(Do not go into project directory)
  3. run command as: react-native init "ProjectName" and it will warn that project directory already exist but you continue.
  4. It will install all updated node modules as well as missing platform (android/ios) folders inside project without disturbing the code already written.
  5. cd "ProjectName" and then cd ios and then run pod install

PS: Take backup of your code in case it changes App.js

How Do I Uninstall Yarn

Try "npm uninstall -g yarnpkg"(global) or "npm uninstall yarnpkg"(local) if you installed it with npm.
That's what worked for me.
If that still doesn't work and you installed it with npm,
do "npm list -g" to check if you installed it globally or "npm list" if you installed it locally.
Hope that helps anyone having this problem. :D

EDIT: Found something if you installed yarn with .msi executable you have to install it the normal windows way.

Job for mysqld.service failed See "systemctl status mysqld.service"

These are the steps I took to correct this:

Back up your my.cnf file in /etc/mysql and remove or rename it

sudo mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak

Remove the folder /etc/mysql/mysql.conf.d/ using

sudo rm -r /etc/mysql/mysql.conf.d/

Verify you don't have a my.cnf file stashed somewhere else (I did in my home dir!) or in /etc/alternatives/my.cnf use

sudo find / -name my.cnf

Now reinstall every thing

sudo apt purge mysql-server mysql-server-5.7 mysql-server-core-5.7
sudo apt install mysql-server

In case your syslog shows an error like "mysqld: Can't read dir of '/etc/mysql/conf.d/'" create a symbolic link:

sudo ln -s /etc/mysql/mysql.conf.d /etc/mysql/conf.d

Then the service should be able to start with sudo service mysql start.

I hope it work

Installation failed with message Invalid File

Hopefully, this should solve your problem.

Do follow the following steps.

1. Clean your Project

Cleaning the project

2. Rebuild your project

Rebuilding the project

3. Finally Build and Run your project

Chrome violation : [Violation] Handler took 83ms of runtime

Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout like below:

[Violation] 'setTimeout' handler took 43129ms

That number (43129ms) depends on how long you stop in your async function

How to uninstall Golang?

only tab
rm -rvf /usr/local/go/
not works well, but
sudo rm -rvf /usr/local/go/
do.

How to uninstall Anaconda completely from macOS

Open the terminal and remove your entire Anaconda directory, which will have a name such as “anaconda2” or “anaconda3”, by entering the following command: rm -rf ~/anaconda3. Then remove conda with command "conda uninstall" https://conda.io/docs/commands/conda-uninstall.html.

Equivalent to AssemblyInfo in dotnet core/csproj

As you've already noticed, you can control most of these settings in .csproj.

If you'd rather keep these in AssemblyInfo.cs, you can turn off auto-generated assembly attributes.

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> 

If you want to see what's going on under the hood, checkout Microsoft.NET.GenerateAssemblyInfo.targets inside of Microsoft.NET.Sdk.

Unable to preventDefault inside passive event listener

To still be able to scroll this worked for me

if (e.changedTouches.length > 1) e.preventDefault();

Unable to set default python version to python3 in ubuntu

Do

cd ~
gedit .bash_aliases

then write either

alias python=python3

or

alias python='/usr/bin/python3'

Save the file, close the terminal and open it again.
You should be fine now! Link

What is correct media query for IPad Pro?

Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.

You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.

For instance, the iPad Pro (12.9") would have the following media queries:

/* Landscape */ 
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }

Whereas the iPad Pro (10.5") will have:

/* Landscape */ 
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }

How do I get rid of the b-prefix in a string in python?

On python 3.6 with django 2.0, decode on a byte literal does not works as expected. Yeah i get the right result when i print it, but the b'value' is still there even if you print it right.

This is what im encoding

uid': urlsafe_base64_encode(force_bytes(user.pk)),

This is what im decoding:

uid = force_text(urlsafe_base64_decode(uidb64))

This is what django 2.0 says :

urlsafe_base64_encode(s)[source]

Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.

urlsafe_base64_decode(s)[source]

Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.


This is my account_activation_email_test.html file

{% autoescape off %}
Hi {{ user.username }},

Please click on the link below to confirm your registration:

http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}

This is my console response:

Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Activate Your MySite Account From: webmaster@localhost To: [email protected] Date: Fri, 20 Apr 2018 06:26:46 -0000 Message-ID: <152420560682.16725.4597194169307598579@Dash-U>

Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/

as you can see uid = b'MjU'

expected uid = MjU


test in console:

$ python
Python 3.6.4 (default, Apr  7 2018, 00:45:33) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>> 

After investigating it seems like its related to python 3. My workaround was quite simple:

'uid': user.pk,

i receive it as uidb64 on my activate function:

user = User.objects.get(pk=uidb64)

and voila:

Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: [email protected]
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>


Hi testuser,

Please click on the link below to confirm your registration:

http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/

now it works fine. :)

Moving Panel in Visual Studio Code to right side

For people looking for an answer (on how to move the side panel):

You can press

ctrl + , (Or cmd + , on OSX)

and add the following option to your user settings JSON file:

"workbench.sideBar.location": "right"

SideBar on the left

Clear git local cache

All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area

git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.

You must explicitly remove them and then commit your removal manually in order to fully ignore them.


enter image description here

enter image description here

Remove all items from a FormArray in Angular

Or you can simply clear the controls

this.myForm= {
     name: new FormControl(""),
     desc: new FormControl(""),
     arr: new FormArray([])
}

Add something array

const arr = <FormArray>this.myForm.controls.arr;
arr.push(new FormControl("X"));

Clear the array

const arr = <FormArray>this.myForm.controls.arr;
arr.controls = [];

When you have multiple choices selected and clear, sometimes it doesn't update the view. A workaround is to add

arr.removeAt(0)

UPDATE

A more elegant solution to use form arrays is using a getter at the top of your class and then you can access it.

get inFormArray(): FormArray {
    this.myForm.get('inFormArray') as FormArray;
}

And to use it in a template

<div *ngFor="let c of inFormArray; let i = index;" [formGroup]="i">
other tags...
</div>

Reset:

inFormArray.reset();

Push:

inFormArray.push(new FormGroup({}));

Remove value at index: 1

inFormArray.removeAt(1);

UPDATE 2:

Get partial object, get all errors as JSON and many other features, use the NaoFormsModule

Moving all files from one directory to another using Python

For example, if I wanted to move all .txt files from one location to another ( on a Windows OS for instance ) I would do it something like this:

import shutil
import os,glob

inpath = 'R:/demo/in' 
outpath = 'R:/demo/out'

os.chdir(inpath)
for file in glob.glob("*.txt"):

    shutil.move(inpath+'/'+file,outpath)

Scrolling to element using webdriver?

This can be done using driver.execute_script():-

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

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Nested routes with react router v4 / v5

I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

How to remove components created with Angular-CLI

You should remove your component manually, that is...

[name].component.ts
[name].component.html  // if you've used templateUrl in your component
[name].component.spec.ts  // if you've created test file
[name].component.[css or scss]  // if you've used styleUrls in your component

If you have all that files in a folder, delete the folder directly.

Then you need to go to the module which use that component and delete

import { [component_name] } from ...

and the component on the declarations array

That's all. Hope that helps

How to use requirements.txt to install all dependencies in a python project

If you are using Linux OS:

  1. Remove matplotlib==1.3.1 from requirements.txt
  2. Try to install with sudo apt-get install python-matplotlib
  3. Run pip install -r requirements.txt (Python 2), or pip3 install -r requirements.txt (Python 3)
  4. pip freeze > requirements.txt

If you are using Windows OS:

  1. python -m pip install -U pip setuptools
  2. python -m pip install matplotlib

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

https://vuejs.org/v2/api/#Vue-delete

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

tsconfig.json: Build:No inputs were found in config file

I'm not using TypeScript in this project at all so it's quite frustrating having to deal with this. I fixed this by adding a tsconfig.json and an empty file.ts file to the project root. The tsconfig.json contains this:

{
  "compilerOptions": {

    "allowJs": false,
    "noEmit": true // Do not compile the JS (or TS) files in this project on build

  },
  "compileOnSave": false,
  "exclude": [ "src", "wwwroot" ],
  "include": [ "file.ts" ]
}

In Chrome 55, prevent showing Download button for HTML 5 video

May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)

They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

CR LF notepad++ removal

"View -> Show Symbol -> uncheck Show All characters" may not work if you have pending update for notepad++. So update Notepad++ and then View -> Show Symbol -> uncheck Show All characters

Hope this is helpful!

React - Display loading screen while DOM is rendering?

This will happen before ReactDOM.render() takes control of the root <div>. I.e. your App will not have been mounted up to that point.

So you can add your loader in your index.html file inside the root <div>. And that will be visible on the screen until React takes over.

You can use whatever loader element works best for you (svg with animation for example).

You don't need to remove it on any lifecycle method. React will replace any children of its root <div> with your rendered <App/>, as we can see in the GIF below.

Example on CodeSandbox

enter image description here

index.html

<head>
  <style>
    .svgLoader {
      animation: spin 0.5s linear infinite;
      margin: auto;
    }
    .divLoader {
      width: 100vw;
      height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
</head>

<body>
  <div id="root">
    <div class="divLoader">
      <svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
        <path fill="lightblue"
          d="PATH FOR THE LOADER ICON"
        />
      </svg>
    </div>
  </div>
</body>

index.js

Using debugger to inspect the page before ReactDOM.render() runs.

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

debugger; // TO INSPECT THE PAGE BEFORE 1ST RENDER

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Remove quotes from String in Python

You can use eval() for this purpose

>>> url = "'http address'"
>>> eval(url)
'http address'

while eval() poses risk , i think in this context it is safe.

Removing object from array in Swift 3

Another nice and useful solution is to create this kind of extension:

extension Array where Element: Equatable {

    @discardableResult mutating func remove(object: Element) -> Bool {
        if let index = index(of: object) {
            self.remove(at: index)
            return true
        }
        return false
    }

    @discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
        if let index = self.index(where: { (element) -> Bool in
            return predicate(element)
        }) {
            self.remove(at: index)
            return true
        }
        return false
    }

}

In this way, if you have your array with custom objects:

let obj1 = MyObject(id: 1)
let obj2 = MyObject(id: 2)
var array: [MyObject] = [obj1, obj2]

array.remove(where: { (obj) -> Bool in
    return obj.id == 1
})
// OR
array.remove(object: obj2) 

YouTube Autoplay not working

Remove the spaces before the autoplay=1:

src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

Maximum call stack size exceeded on npm install

For those having this issue when building a Docker image with Jenkins (or any CI), make sure the package-lock.json is also copied to the container.

COPY ./src/package*.json /home/node/
RUN npm install

For us, the install actually went fine, the error only occurred when running npm prune production for the production image.

How to install Visual C++ Build tools?

I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.

enter image description here

I hope it helps save others time!

How can I mock an ES6 module import using Jest?

The claims that you have to mock it at the top of your file are false.

Mock a named ES Import:

// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';

// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
  useWalkthroughAnimations: jest.fn()
}));

// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });

remove item from stored array in angular 2

//declaration 
list: Array<any> = new Array<any>(); 

//remove item from an array 
removeitem() 
{
const index = this.list.findIndex(user => user._id === 2); 
this.list.splice(index, 1); 
}

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Even without looking at assembly, the most obvious reason is that /= 2 is probably optimized as >>=1 and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.

Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2 as >>=1 would be the best 1st place to look.


On an unrelated note, if n is odd, the expression n*3+1 will always be even. So there is no need to check. You can change that branch to

{
   n = (n*3+1) >> 1;
   count += 2;
}

So the whole statement would then be

if (n & 1)
{
    n = (n*3 + 1) >> 1;
    count += 2;
}
else
{
    n >>= 1;
    ++count;
}

Removing object properties with Lodash

To select (or remove) object properties that satisfy a given condition deeply, you can use something like this:

function pickByDeep(object, condition, arraysToo=false) {
  return _.transform(object, (acc, val, key) => {
    if (_.isPlainObject(val) || arraysToo && _.isArray(val)) {
      acc[key] = pickByDeep(val, condition, arraysToo);
    } else if (condition(val, key, object)) {
      acc[key] = val;
    }
  });
}

https://codepen.io/aercolino/pen/MWgjyjm

Delete commit on gitlab

  1. git reset --hard CommitId
  2. git push -f origin master

1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.

Note: Don't forget to add -f in push otherwise it will be rejected.

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

How to request Location Permission at runtime

Location permission privacy change in Android 10 or Android Q.

We have to define additional ACCESS_BACKGROUND_LOCATION permission if user wants to access their current location in background so user needs to granted permission runtime also in requestPermission()

If we are using lower than Android 10 device then ACCESS_BACKGROUND_LOCATION permission allow automatically with ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission

This tabular format might be easy to understand what if we don't specify ACCESS_BACKGROUND_LOCATION in manifest file.

enter image description here

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> // here we defined ACCESS_BACKGROUND_LOCATION for Android 10 device

MainActivity.java
Call checkRunTimePermission() in onCreate() or onResume()

public void checkRunTimePermission() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || 
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED||
             ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                gpsTracker = new GPSTracker(context);

        } else {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                        10);
        }
   } else {
            gpsTracker = new GPSTracker(context); //GPSTracker is class that is used for retrieve user current location
   }
}

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 10) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            gpsTracker = new GPSTracker(context);
        } else {
            if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION)) {
                // If User Checked 'Don't Show Again' checkbox for runtime permission, then navigate user to Settings
                AlertDialog.Builder dialog = new AlertDialog.Builder(context);
                dialog.setTitle("Permission Required");
                dialog.setCancelable(false);
                dialog.setMessage("You have to Allow permission to access user location");
                dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package",
                                context.getPackageName(), null));
                        //i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivityForResult(i, 1001);
                    }
                });
                AlertDialog alertDialog = dialog.create();
                alertDialog.show();
            }
            //code for deny
        }
    }
}

@Override
public void startActivityForResult(Intent intent, int requestCode) {
    super.startActivityForResult(intent, requestCode);
    switch (requestCode) {
        case 1001:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED 
                        || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    gpsTracker = new GPSTracker(context);
                    if (gpsTracker.canGetLocation()) {
                        latitude = gpsTracker.getLatitude();
                        longitude = gpsTracker.getLongitude();
                    }
                } else {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION},10);
                }
            }
            break;
        default:
            break;
    }
}

build.gradle (app level)

android {
    compileSdkVersion 29 //should be >= 29
    buildToolsVersion "29.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.example.runtimepermission"
        minSdkVersion 21
        targetSdkVersion 29 //should be >= 29
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
}

Here you can find GPSTracker.java file code

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

Default FirebaseApp is not initialized

to me it was upgrading dependencies of com.google.gms:google-services inside build.gradle to

buildscript {
repositories {
    jcenter()
    mavenCentral()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.3.2'
    classpath 'com.google.gms:google-services:4.2.0'

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

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

Append an empty row in dataframe using pandas

Assuming df is your dataframe,

df_prime = pd.concat([df, pd.DataFrame([[np.nan] * df.shape[1]], columns=df.columns)], ignore_index=True)

where df_prime equals df with an additional last row of NaN's.

Note that pd.concat is slow so if you need this functionality in a loop, it's best to avoid using it. In that case, assuming your index is incremental, you can use

df.loc[df.iloc[-1].name + 1,:] = np.nan

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

Deprecation warning in Moment.js - Not in a recognized ISO format

const dateFormat = 'MM-DD-YYYY';

const currentDateStringType = moment(new Date()).format(dateFormat);
    
const currentDate = moment(new Date() ,dateFormat);  // use this 

moment.suppressDeprecationWarnings = true;

How to completely uninstall Android Studio from windows(v10)?

Uninstall your android studio in control panel and remove all data in your file manager about android studio.

a = open("file", "r"); a.readline() output without \n

A solution, can be:

with open("file", "r") as fd:
    lines = fd.read().splitlines()

You get the list of lines without "\r\n" or "\n".

Or, use the classic way:

with open("file", "r") as fd:
    for line in fd:
        line = line.strip()

You read the file, line by line and drop the spaces and newlines.

If you only want to drop the newlines:

with open("file", "r") as fd:
    for line in fd:
        line = line.replace("\r", "").replace("\n", "")

Et voilà.

Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open.

See the documentation of io.open.

So, you can use:

with io.open("file", "r", newline=None) as fd:
    for line in fd:
        line = line.replace("\n", "")

When the newline parameter is None: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

Usually it happen in TochableHighlight. Anyway error mean that you must used single element inside the whatever component.

Solution : You can use single view inside parent and anything can be used inside that View. See the attached picture

enter image description here

How to get element's width/height within directives and component?

For a bit more flexibility than with micronyks answer, you can do it like that:

1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

<p #myIdentifier>
  my-component works!
</p>

2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}

Security

About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

Angular2: Cannot read property 'name' of undefined

The variable selectedHero is null in the template so you cannot bind selectedHero.name as is. You need to use the elvis operator ?. for this case:

<input [ngModel]="selectedHero?.name" (ngModelChange)="selectedHero.name = $event" />

The separation of the [(ngModel)] into [ngModel] and (ngModelChange) is also needed because you can't assign to an expression that uses the elvis operator.

I also think you mean to use:

<h2>{{selectedHero?.name}} details!</h2>

instead of:

<h2>{{hero.name}} details!</h2>

Apache POI error loading XSSFWorkbook class

Yeah, resolved the exception by adding commons-collections4-4.1 jar file to the CLASSPATH user varible of system. Downloaded from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

First check the type of compression using the file command:

file name_name.tgz

O/P- If output is " XZ compressed data"

Then use tar xf <archive name> to unzip the file, e.g.

  • tar xf archive.tar.xz

  • tar xf archive.tar.gz

  • tar xf archive.tar

  • tar xf archive.tgz

How do I kill the process currently using a port on localhost in Windows?

the first step

netstat -vanp tcp | grep 8888

example

tcp4     0      0    127.0.0.1.8888   *.*    LISTEN      131072 131072  76061    0
tcp46    0      0    *.8888           *.*    LISTEN      131072 131072  50523    0

the second step: find your PIDs and kill them

in my case

sudo kill -9 76061 50523

How to use addTarget method in swift 3

the Demo from Apple document. https://developer.apple.com/documentation/swift/using_objective-c_runtime_features_in_swift

import UIKit
class MyViewController: UIViewController {
    let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))

    override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // without parameter style
        let action = #selector(MyViewController.tappedButton)
        // with parameter style
        // #selector(MyViewController.tappedButton(_:))
        myButton.addTarget(self, action: action, forControlEvents: .touchUpInside)
    }

    @objc func tappedButton(_ sender: UIButton?) {
        print("tapped button")
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

In reactJS, how to copy text to clipboard?

If you want to select from the DIV instead of the text field, here is the code. The "code" is the value that has to be copied

import React from 'react'
class CopyToClipboard extends React.Component {

  copyToClipboard(code) {
    var textField = document.createElement('textarea')
    textField.innerText = code
    document.body.appendChild(textField)
    textField.select()
    document.execCommand('copy')
    textField.remove()
  }
  render() {
    return (
      <div onClick={this.copyToClipboard.bind(this, code)}>
        {code}
      </div>

    )
  }
}

export default CopyToClipboard

Remove a modified file from pull request

You would want to amend the commit and then do a force push which will update the branch with the PR.

Here's how I recommend you do this:

  1. Close the PR so that whomever is reviewing it doesn't pull it in until you've made your changes.
  2. Do a Soft reset to the commit before your unwanted change (if this is the last commit you can use git reset --soft HEAD^ or if it's a different commit, you would want to replace 'HEAD^' with the commit id)
  3. Discard (or undo) any changes to the file that you didn't intend to update
  4. Make a new commit git commit -a -c ORIG_HEAD
  5. Force Push to your branch
  6. Re-Open Pull Request

The now that your branch has been updated, the Pull Request will include your changes.

Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.

http post - how to send Authorization header?

you need RequestOptions

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

for more check this link

How to convert JSON object to an Typescript array?

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

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

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

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

... or even easier:

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

Error: Unexpected value 'undefined' imported by the module

I was facing the same problem. Issue was that I was importing some class from index.ts

    import {className} from '..shared/index'

index.ts contain the export statement

    export * from './models';

I changed it to the .ts file which contain the actual class object

    import {className} from '..shared/model'

and it resolved.

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

In my case, this problem occured because I did npm install with another system user in my project folder before. Gulp was already installed globally. After deleting folder /node_modules/ in my project, and running npm install with the current user, it worked.

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

The CLI's webpack config can now be ejected. Check Anton Nikiforov's answer.


outdated:

You can hack the config template in angular-cli/addon/ng2/models. There's no official way to modify the webpack config as of now.

There's a closed "wont-fix" issue on github about this: https://github.com/angular/angular-cli/issues/1656

Remove menubar from Electron app

Use this:

mainWindow = new BrowserWindow({width: 640, height: 360})
mainWindow.setMenuBarVisibility(false)

Reference: https://github.com/electron/electron/issues/1415

I tried mainWindow.setMenu(null), but it didn't work.

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

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

Is there a quick change tabs function in Visual Studio Code?

@Combii I found a way to swap

CMD+1, CMD+2, CMD+3 with CTRL+1, CTRL+2, CTRL+3, ...

In macOS, go to:

Code > Preferences > Keyboard Shortcuts

On that page, click the button on the top right of the page...

edit keybindings.json button

and append the configuration below, then save.

[
    {
        "key": "cmd+0",
        "command": "workbench.action.openLastEditorInGroup"
    },
    {
        "key": "cmd+1",
        "command": "workbench.action.openEditorAtIndex1"
    },
    {
        "key": "cmd+2",
        "command": "workbench.action.openEditorAtIndex2"
    },
    {
        "key": "cmd+3",
        "command": "workbench.action.openEditorAtIndex3"
    },
    {
        "key": "cmd+4",
        "command": "workbench.action.openEditorAtIndex4"
    },
    {
        "key": "cmd+5",
        "command": "workbench.action.openEditorAtIndex5"
    },
    {
        "key": "cmd+6",
        "command": "workbench.action.openEditorAtIndex6"
    },
    {
        "key": "cmd+7",
        "command": "workbench.action.openEditorAtIndex7"
    },
    {
        "key": "cmd+8",
        "command": "workbench.action.openEditorAtIndex8"
    },
    {
        "key": "cmd+9",
        "command": "workbench.action.openEditorAtIndex9"
    },
    {
        "key": "ctrl+1",
        "command": "workbench.action.focusFirstEditorGroup"
    },
    {
        "key": "ctrl+2",
        "command": "workbench.action.focusSecondEditorGroup"
    },
    {
        "key": "ctrl+3",
        "command": "workbench.action.focusThirdEditorGroup"
    }
]

You now can use CMD+[1-9] to switch between tabs and CTRL+[1-3] to focus editor groups! Hope this answer is helpful.

Body of Http.DELETE request in Angular2

You are actually able to fool Angular2 HTTP into sending a body with a DELETE by using the request method. This is how:

let body = {
    target: targetId,
    subset: "fruits",
    reason: "rotten"
};

let options = new RequestOptionsArgs({ 
    body: body,
    method: RequestMethod.Delete
  });

this.http.request('http://testAPI:3000/stuff', options)
    .subscribe((ok)=>{console.log(ok)});

Note, you will have to set the request method in the RequestOptionsArgs and not in http.request's alternative first parameter Request. That for some reason yields the same result as using http.delete

I hope this helps and that I am not to late. I think the angular guys are wrong here to not allow a body to be passed with delete, even though it is discouraged.

implement addClass and removeClass functionality in angular2

Try to use it via [ngClass] property:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = true;
      return $status;
}

Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type

as follows :

public function saveFormSummary(Request $request) {
      ... 
      $status = "true";
      return $status;
}

Xampp-mysql - "Table doesn't exist in engine" #1932

  1. stop mysql
  2. copy xampp\mysql\data\ib* from old server to new server
  3. start mysql

How to read XML using XPath in Java

Read XML file using XPathFactory, SAXParserFactory and StAX (JSR-173).

Using XPath get node and its child data.

public static void main(String[] args) {
    String xml = "<soapenv:Body xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>"
            + "<Yash:Data xmlns:Yash='http://Yash.stackoverflow.com/Services/Yash'>"
            + "<Yash:Tags>Java</Yash:Tags><Yash:Tags>Javascript</Yash:Tags><Yash:Tags>Selenium</Yash:Tags>"
            + "<Yash:Top>javascript</Yash:Top><Yash:User>Yash-777</Yash:User>"
            + "</Yash:Data></soapenv:Body>";
    String jsonNameSpaces = "{'soapenv':'http://schemas.xmlsoap.org/soap/envelope/',"
            + "'Yash':'http://Yash.stackoverflow.com/Services/Yash'}";
    String xpathExpression = "//Yash:Data";

    Document doc1 = getDocument(false, "fileName", xml);
    getNodesFromXpath(doc1, xpathExpression, jsonNameSpaces);
    System.out.println("\n===== ***** =====");
    Document doc2 = getDocument(true, "./books.xml", xml);
    getNodesFromXpath(doc2, "//person", "{}");
}
static Document getDocument( boolean isFileName, String fileName, String xml ) {
    Document doc = null;
    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        if( isFileName ) {
            File file = new File( fileName );
            FileInputStream stream = new FileInputStream( file );
            doc = builder.parse( stream );
        } else {
            doc = builder.parse( string2Source( xml ) );
        }
    } catch (SAXException | IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return doc;
}

/**
 * ELEMENT_NODE[1],ATTRIBUTE_NODE[2],TEXT_NODE[3],CDATA_SECTION_NODE[4],
 * ENTITY_REFERENCE_NODE[5],ENTITY_NODE[6],PROCESSING_INSTRUCTION_NODE[7],
 * COMMENT_NODE[8],DOCUMENT_NODE[9],DOCUMENT_TYPE_NODE[10],DOCUMENT_FRAGMENT_NODE[11],NOTATION_NODE[12]
 */
public static void getNodesFromXpath( Document doc, String xpathExpression, String jsonNameSpaces ) {
    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        JSONObject namespaces = getJSONObjectNameSpaces(jsonNameSpaces);
        if ( namespaces.size() > 0 ) {
            NamespaceContextImpl nsContext = new NamespaceContextImpl();

            Iterator<?> key = namespaces.keySet().iterator();
            while (key.hasNext()) { // Apache WebServices Common Utilities
                String pPrefix = key.next().toString();
                String pURI = namespaces.get(pPrefix).toString();
                nsContext.startPrefixMapping(pPrefix, pURI);
            }
            xpath.setNamespaceContext(nsContext );
        }

        XPathExpression compile = xpath.compile(xpathExpression);
        NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);
        displayNodeList(nodeList);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

static void displayNodeList( NodeList nodeList ) {
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String NodeName = node.getNodeName();

        NodeList childNodes = node.getChildNodes();
        if ( childNodes.getLength() > 1 ) {
            for (int j = 0; j < childNodes.getLength(); j++) {

                Node child = childNodes.item(j);
                short nodeType = child.getNodeType();
                if ( nodeType == 1 ) {
                    System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
                }
            }
        } else {
            System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
        }

    }
}
static InputSource string2Source( String str ) {
    InputSource inputSource = new InputSource( new StringReader( str ) );
    return inputSource;
}
static JSONObject getJSONObjectNameSpaces( String jsonNameSpaces ) {
    if(jsonNameSpaces.indexOf("'") > -1)    jsonNameSpaces = jsonNameSpaces.replace("'", "\"");
    JSONParser parser = new JSONParser();
    JSONObject namespaces = null;
    try {
        namespaces = (JSONObject) parser.parse(jsonNameSpaces);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return namespaces;
}

XML Document

<?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
  <first>Yash</first>
  <last>M</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>

Out put for the given XPathExpression:

String xpathExpression = "//person/first";
/*OutPut:
 Node Name:[first], Text[Yash] 
 Node Name:[first], Text[Bill] 
 Node Name:[first], Text[Steve] */

String xpathExpression = "//person";
/*OutPut:
     Node Name:[first], Text[Yash] 
     Node Name:[last], Text[M] 
     Node Name:[age], Text[22] 
     Node Name:[first], Text[Bill] 
     Node Name:[last], Text[Gates] 
     Node Name:[age], Text[46] 
     Node Name:[first], Text[Steve] 
     Node Name:[last], Text[Jobs] 
     Node Name:[age], Text[40] */

String xpathExpression = "//Yash:Data";
/*OutPut:
     Node Name:[Yash:Tags], Text[Java] 
     Node Name:[Yash:Tags], Text[Javascript] 
     Node Name:[Yash:Tags], Text[Selenium] 
     Node Name:[Yash:Top], Text[javascript] 
     Node Name:[Yash:User], Text[Yash-777] */

See this link for our own Implementation of NamespaceContext

How to create a responsive image that also scales up in Bootstrap 3

Bootstrap's responsive image class sets max-width to 100%. This limits its size, but does not force it to stretch to fill parent elements larger than the image itself. You'd have to use the width attribute to force upscaling.

http://getbootstrap.com/css/#images-responsive

400 vs 422 response to POST of data

Your case: HTTP 400 is the right status code for your case from REST perspective as its syntactically incorrect to send sales_tax instead of tax, though its a valid JSON. This is normally enforced by most of the server side frameworks when mapping the JSON to objects. However, there are some REST implementations that ignore new key in JSON object. In that case, a custom content-type specification to accept only valid fields can be enforced by server-side.

Ideal Scenario for 422:

In an ideal world, 422 is preferred and generally acceptable to send as response if the server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the data because its semantically erroneous.

Situations of 400 over 422:

Remember, the response code 422 is an extended HTTP (WebDAV) status code. There are still some HTTP clients / front-end libraries that aren't prepared to handle 422. For them, its as simple as "HTTP 422 is wrong, because it's not HTTP". From the service perspective, 400 isn't quite specific.

In enterprise architecture, the services are deployed mostly on service layers like SOA, IDM, etc. They typically serve multiple clients ranging from a very old native client to a latest HTTP clients. If one of the clients doesn't handle HTTP 422, the options are that asking the client to upgrade or change your response code to HTTP 400 for everyone. In my experience, this is very rare these days but still a possibility. So, a careful study of your architecture is always required before deciding on the HTTP response codes.

To handle situation like these, the service layers normally use versioning or setup configuration flag for strict HTTP conformance clients to send 400, and send 422 for the rest of them. That way they provide backwards compatibility support for existing consumers but at the same time provide the ability for the new clients to consume HTTP 422.


The latest update to RFC7321 says:

The 400 (Bad Request) status code indicates that the server cannot or
   will not process the request due to something that is perceived to be
   a client error (e.g., malformed request syntax, invalid request
   message framing, or deceptive request routing).

This confirms that servers can send HTTP 400 for invalid request. 400 doesn't refer only to syntax error anymore, however, 422 is still a genuine response provided the clients can handle it.

How can I read Chrome Cache files?

I had some luck with this open-source Python project, seemingly inactive: https://github.com/JRBANCEL/Chromagnon

I ran:

python2 Chromagnon/chromagnonCache.py path/to/Chrome/Cache -o browsable_cache/

And I got a locally-browsable extract of all my open tabs cache.

How can you float: right in React Native?

why does the Text take up the full space of the View, instead of just the space for "Hello"?

Because the View is a flex container and by default has flexDirection: 'column' and alignItems: 'stretch', which means that its children should be stretched out to fill its width.

(Note, per the docs, that all components in React Native are display: 'flex' by default and that display: 'inline' does not exist at all. In this way, the default behaviour of a Text within a View in React Native differs from the default behaviour of span within a div on the web; in the latter case, the span would not fill the width of the div because a span is an inline element by default. There is no such concept in React Native.)

How can the Text be floated / aligned to the right?

The float property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:

1. Use textAlign: 'right' on the Text element

<View>
  <Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>

(This approach doesn't change the fact that the Text fills the entire width of the View; it just right-aligns the text within the Text.)

2. Use alignSelf: 'flex-end' on the Text

<View>
  <Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>

This shrinks the Text element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View.

3. Use alignItems: 'flex-end' on the View

<View style={{alignItems: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

This is equivalent to setting alignSelf: 'flex-end' on all the View's children.

4. Use flexDirection: 'row' and justifyContent: 'flex-end' on the View

<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

flexDirection: 'row' sets the main direction of layout to be horizontal instead of vertical; justifyContent is just like alignItems, but controls alignment in the main direction instead of the cross direction.

5. Use flexDirection: 'row' on the View and marginLeft: 'auto' on the Text

<View style={{flexDirection: 'row'}}>
  <Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>

This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.

6. Use position: 'absolute' and right: 0 on the Text:

<View>
  <Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>

Like in real CSS, this takes the Text "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View by default (although you can explicitly set a distance from the top of the View using the top style property).


Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.

How to update a claim in ASP.NET Identity?

Another (async) approach, using Identity's UserManager and SigninManager to reflect the change in the Identity cookie (and to optionally remove claims from db table AspNetUserClaims):

// Get User and a claims-based identity
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
var Identity = new ClaimsIdentity(User.Identity);

// Remove existing claim and replace with a new value
await UserManager.RemoveClaimAsync(user.Id, Identity.FindFirst("AccountNo"));
await UserManager.AddClaimAsync(user.Id, new Claim("AccountNo", value));

// Re-Signin User to reflect the change in the Identity cookie
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

// [optional] remove claims from claims table dbo.AspNetUserClaims, if not needed
var userClaims = UserManager.GetClaims(user.Id);
if (userClaims.Any())
{
  foreach (var item in userClaims)
  {
    UserManager.RemoveClaim(user.Id, item);
  }
}

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

JavaScript ES6 promise for loop

As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.

Secondly, each promise that is created with new Promise needs to be resolved with a call to resolve (or reject). This should be done when the timer expires. That will trigger any then callback you would have on that promise. And such a then callback (or await) is a necessity in order to implement the chain.

With those ingredients, there are several ways to perform this asynchronous chaining:

  1. With a for loop that starts with an immediately resolving promise

  2. With Array#reduce that starts with an immediately resolving promise

  3. With a function that passes itself as resolution callback

  4. With ECMAScript2017's async / await syntax

  5. With ECMAScript2020's for await...of syntax

See a snippet and comments for each of these options below.

1. With for

You can use a for loop, but you must make sure it doesn't execute new Promise synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:

_x000D_
_x000D_
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
    p = p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ));
}
_x000D_
_x000D_
_x000D_

2. With reduce

This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:

_x000D_
_x000D_
[...Array(10)].reduce( (p, _, i) => 
    p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ))
, Promise.resolve() );
_x000D_
_x000D_
_x000D_

This is probably more useful when you actually have an array with data to be used in the promises.

3. With a function passing itself as resolution-callback

Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:

_x000D_
_x000D_
(function loop(i) {
    if (i < 10) new Promise((resolve, reject) => {
        setTimeout( () => {
            console.log(i);
            resolve();
        }, Math.random() * 1000);
    }).then(loop.bind(null, i+1));
})(0);
_x000D_
_x000D_
_x000D_

This creates a function named loop, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.

The call to resolve() will trigger the then callback which will call the function again. loop.bind(null, i+1) is just a different way of saying _ => loop(i+1).

4. With async/await

Modern JS engines support this syntax:

_x000D_
_x000D_
(async function loop() {
    for (let i = 0; i < 10; i++) {
        await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

It may look strange, as it seems like the new Promise() calls are executed synchronously, but in reality the async function returns when it executes the first await. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await, until it encounters the next one, and so it continues until the loop finishes.

As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout. It may improve the readability of the code:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

(async function loop() {
    for (let i = 0; i < 10; i++) {
        await delay(Math.random() * 1000);
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

5. With for await...of

With EcmaScript 2020, the for await...of found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
    for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}

(async function loop() {
    for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
_x000D_
_x000D_

Ng-model does not update controller value

"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.

Controller

$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works
}

Template

<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats. The child-scope creates it's own value and a name conflict is born as illustrated here:

See this video clip for more: https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

How can I call a function using a function pointer?

Note that when you say:

bool (*a)();

you are declaring a of type "pointer to function returning bool and taking an unspecified number of parameters". Assuming bool is defined (maybe you're using C99 and have included stdbool.h, or it may be a typedef), this may or may not be what you want.

The problem here is that there is no way for the compiler to now check if a is assigned to a correct value. The same problem exists with your function declarations. A(), B(), and C() are all declared as functions "returning bool and taking an unspecified number of parameters".

To see the kind of problems that may have, let's write a program:

#include <stdio.h>

int test_zero(void)
{
    return 42;
}

static int test_one(char *data)
{
    return printf("%s\n", data);
}

int main(void)
{
    /* a is of type "pointer to function returning int
       and taking unspecified number of parameters */
    int (*a)();

    /* b is of type "pointer to function returning int
       and taking no parameters */
    int (*b)(void);

    /* This is OK */
    a = test_zero;
    printf("a: %d\n", a());

    a = test_one; /* OK, since compiler doesn't check the parameters */
    printf("a: %d\n", a()); /* oops, wrong number of args */

    /* This is OK too */
    b = test_zero;
    printf("b: %d\n", b());

    /* The compiler now does type checking, and sees that the
       assignment is wrong, so it can warn us */
    b = test_one;
    printf("b: %d\n", b()); /* Wrong again */

    return 0;
}

When I compile the above with gcc, it says:

warning: assignment from incompatible pointer type

for the line b = test_one;, which is good. There is no warning for the corresponding assignment to a.

So, you should declare your functions as:

bool A(void);
bool B(void);
bool C(void);

And then the variable to hold the function should be declared as:

bool (*choice)(void);

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.

Then you can run the query like this:

alter table table_name drop foreign_key_col_name;

Postgres Error: More than one row returned by a subquery used as an expression

USE LIMIT 1 - so It will return only 1 row. Example

customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

This worked for me. All I had to do is uninstall mysql2 gem and install it again using the below commands

gem uninstall mysql2
gem install mysql2 -v '0.3.18' -- --with-mysql-config=/usr/local/Cellar/[email protected]/5.7.28/bin/mysql_config

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

The brute force method of generating every single possible board and scoring it based on the boards it later produces further down the tree doesn't require much memory, especially once you recognize that 90 degree board rotations are redundant, as are flips about the vertical, horizontal, and diagonal axis.

Once you get to that point, there's something like less than 1k of data in a tree graph to describe the outcome, and thus the best move for the computer.

-Adam

Set margins in a LinearLayout programmatically

Here a single line Solution:

((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));

Using Panel or PlaceHolder

A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.

"Insert if not exists" statement in SQLite

If you have a table called memos that has two columns id and text you should be able to do like this:

INSERT INTO memos(id,text) 
SELECT 5, 'text to insert' 
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');

If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.

I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.

I would advice that you instead design your table so that no duplicates are allowed as explained in @CLs answer below.

Can Windows Containers be hosted on linux?

You can use Windows Containers inside a virtual machine (the guest OS should match the requirements - Windows 10 Pro or Windows 2016).

For example you can use VirtualBox, just enable Hyper-V inside System / Acceleration / Paravirtualization Interface.

After that if Docker doesn't start up because of an error, use the "Switch to Windows containers..." in the settings.

(this could be moved as a comment to the accepted answer, but I don't have enough reputation to do so)

Rails: update_attribute vs update_attributes

update_attribute

This method update single attribute of object without invoking model based validation.

obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”

update_attributes

This method update multiple attribute of single object and also pass model based validation.

attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)

Hope this answer will clear out when to use what method of active record.

Change form size at runtime in C#

You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:

button1_Click(object sender, EventArgs e)
{
    // This will change the Form's Width and Height, respectively.
    this.Size = new Size(420, 200);
}

How does Facebook Sharer select Images and other metadata when sharing my URL?

Put the following tag in the head:

<link rel="image_src" href="/path/to/your/image"/>

From http://www.facebook.com/share_partners.php

As far as what it chooses as the default in the absence of this tag, I'm not sure.

Turn off deprecated errors in PHP 5.3

I just faced a similar problem where a SEO plugin issued a big number of warnings making my blog disk use exceed the plan limit.

I found out that you must include the error_reporting command after the wp-settings.php require in the wp-config.php file:

   require_once( ABSPATH .'wp-settings.php' );
   error_reporting( E_ALL ^ ( E_NOTICE | E_WARNING | E_DEPRECATED ) );

by doing this no more warnings, notices nor deprecated lines are appended to your error log file!

Tested on WordPress 3.8 but I guess it works for every installation.

Pass parameters in setInterval function

     setInterval(function(a,b,c){

          console.log(a + b +c);  

      }, 500, 1,2,3);

           //note the console will  print 6
          //here we are passing 1,2,3 for a,b,c arguments
         // tested in node v 8.11 and chrome 69

Safe navigation operator (?.) or (!.) and null property paths

Update:

Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352


You can try to write a custom function like that.

The main advantage of the approach is a type-checking and partial intellisense.

export function nullSafe<T, 
    K0 extends keyof T, 
    K1 extends keyof T[K0],
    K2 extends keyof T[K0][K1],
    K3 extends keyof T[K0][K1][K2],
    K4 extends keyof T[K0][K1][K2][K3],
    K5 extends keyof T[K0][K1][K2][K3][K4]>
    (obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
    let result: any = obj;

    const keysCount = arguments.length - 1;
    for (var i = 1; i <= keysCount; i++) {
        if (result === null || result === undefined) return result;
        result = result[arguments[i]];
    }

    return result;
}

And usage (supports up to 5 parameters and can be extended):

nullSafe(a, 'b', 'c');

Example on playground.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

   const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
    const dateObj = new Date();
    const month = monthNames[dateObj.getMonth()];
    const day = String(dateObj.getDate()).padStart(2, '0');
    const year = dateObj.getFullYear();
    const output = month  + '\n'+ day  + ',' + year;

    document.querySelector('.date').textContent = output; 

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

Ansible date variable

Note that the ansible command doesn't collect facts, but the ansible-playbook command does. When running ansible -m setup, the setup module happens to run the fact collection so you get the facts, but running ansible -m command does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.

SQL to add column and comment in table in single command

No, you can't.

There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.

If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.


In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.

SQL> desc sys.com$
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 OBJ#                                      NOT NULL NUMBER
 COL#                                               NUMBER
 COMMENT$                                           VARCHAR2(4000)

SQL>

The column is optional and sys.col$ does not contain comment information.

I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

PHP string concatenation

This should be faster.

while ($personCount < 10) {
    $result .= "{$personCount} people ";
    $personCount++;
}

echo $result;

Spring - @Transactional - What happens in background?

When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).

However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.

As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.

Does that help?

How do you convert a byte array to a hexadecimal string in C?

ZincX's solution adapted to include colon delimiters:

char buf[] = {0,1,10,11};
int i, size = sizeof(buf) / sizeof(char);
char *buf_str = (char*) malloc(3 * size), *buf_ptr = buf_str;
if (buf_str) {
  for (i = 0; i < size; i++)
    buf_ptr += sprintf(buf_ptr, i < size - 1 ? "%02X:" : "%02X\0", buf[i]);
  printf("%s\n", buf_str);
  free(buf_str);
}

How to convert a structure to a byte array in C#?

Have a look at these methods:

byte [] StructureToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);

    byte [] arr = new byte[len];

    IntPtr ptr = Marshal.AllocHGlobal(len);

    Marshal.StructureToPtr(obj, ptr, true);

    Marshal.Copy(ptr, arr, 0, len);

    Marshal.FreeHGlobal(ptr);

    return arr;
}

void ByteArrayToStructure(byte [] bytearray, ref object obj)
{
    int len = Marshal.SizeOf(obj);

    IntPtr i = Marshal.AllocHGlobal(len);

    Marshal.Copy(bytearray,0, i,len);

    obj = Marshal.PtrToStructure(i, obj.GetType());

    Marshal.FreeHGlobal(i);
}

This is a shameless copy of another thread which I found upon Googling!

Update : For more details, check the source

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

Setting default values to null fields when mapping with Jackson

There is no annotation to set default value.
You can set default value only on java class level:

public class JavaObject 
{
    public String notNullMember;

    public String optionalMember = "Value";
}

Convert a Pandas DataFrame to a dictionary

DataFrame.to_dict() converts DataFrame to dictionary.

Example

>>> df = pd.DataFrame(
    {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

See this Documentation for details

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
    myDict[k] = A.get(k, 0)+B.get(k, 0)

Get keys from HashMap in Java

To get keys in HashMap, We have keySet() method which is present in java.util.Hashmap package. ex :

Map<String,String> map = new Hashmap<String,String>();
map.put("key1","value1");
map.put("key2","value2");

// Now to get keys we can use keySet() on map object
Set<String> keys = map.keySet();

Now keys will have your all keys available in map. ex: [key1,key2]

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

Convert StreamReader to byte[]

For everyone saying to get the bytes, copy it to MemoryStream, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader's built in ReadLine() or ReadToEnd()? I saw these weren't even mentioned, and they do everything for you.

I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:

string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";

string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine();  // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();

return path;

If you REALLY need a byte[] instead of a string for some reason, using my example, you can always do:

byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();

return toBytes;

(Returning toBytes instead of path.)

If you don't want ASCII you can easily replace that with UTF8, Unicode, etc.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

error: unknown type name ‘bool’

Just add the following:

#define __USE_C99_MATH

#include <stdbool.h>

Edit and replay XHR chrome/firefox etc?

Updating/completing zszep answer:

After copying the request as cUrl (bash), simply import it in the Postman App:

enter image description here

How can I enable the Windows Server Task Scheduler History recording?

Step 1: Open an elevated Task Scheduler (ie. right-click on the Task Scheduler icon and choose Run as administrator)

Step 2: In the Actions pane (right pane, not the actions tab), click Enable All Tasks History

That's it. Not sure why this isn't on by default, but it isn't.

How to count number of records per day?

select DateAdded, count(CustID)
from tbl
group by DateAdded

about 7-days interval it's DB-depending question

What is the python "with" statement designed for?

The Python with statement is built-in language support of the Resource Acquisition Is Initialization idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.

The with statement creates resources within a scope/block. You write your code using the resources within the block. When the block exits the resources are cleanly released regardless of the outcome of the code in the block (that is whether the block exits normally or because of an exception).

Many resources in the Python library that obey the protocol required by the with statement and so can used with it out-of-the-box. However anyone can make resources that can be used in a with statement by implementing the well documented protocol: PEP 0343

Use it whenever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.

File to import not found or unreadable: compass

I'm seeing this issue using Rails 4.0.2 and compass-rails 1.1.3

I got past this error by moving gem 'compass-rails' outside of the :assets group in my Gemfile

It looks something like this:

# stuff
gem 'compass-rails', '~> 1.1.3'
group :assets do
  # more stuff
end

No internet on Android emulator - why and how to fix?

In order to use internet on emulator if you are setting behind a proxy server perform the following steps:

  1. Go to settings->Wireless & networks->mobile networks->Access Point Names.
  2. Press menu button. an option menu will appear.

  3. from the option menu select New APN.

  4. Click on Name. provide name to apn say My APN.
  5. Click on APN. Enter www.
  6. Click on Proxy. enter your proxy server IP. you can get it from internet explorers internet options menu.
  7. click on Port. enter port number in my case it was 8080. you can get it from internet explorers internet options menu.
  8. Click on User-name. provide user-name in format domain\user-name. generally it is your systems login.
  9. Click on password. provide your systems password.
  10. press menu button again. an option menu will appear.
  11. press save. try n run your browser. hope its work for you it worked for me. good luck.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

You are writing to the file prior to closing your filestream:

using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
   str.BaseStream.Seek(0,SeekOrigin.End); 
   str.Write("mytext.txt.........................");
   str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
   string addtext="this line is added"+Environment.NewLine;

   str.Flush();

}

File.AppendAllText(path,addtext);  //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);

The above code should work, using the methods you are currently using. You should also look into the using statement and wrap your streams in a using block.

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

try putting username in double quote "username", somehow that fixed for me.

Angular 5 Scroll to top on every Route click

if your using mat-sidenav give an id to the router outlet( if you have a parent and child router outlets) and use activate function in it <router-outlet id="main-content" (activate)="onActivate($event)"> and use this 'mat-sidenav-content' query selector to scroll top onActivate(event) { document.querySelector("mat-sidenav-content").scrollTo(0, 0); }

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

ComboBox.SelectedText doesn't give me the SelectedText

From the documentation:

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.

When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.

git clone through ssh

I did : git clone --bare "/GITREPOSITORIES/RepoA" "ssh://luc@EERSTENASDS119J/volume1/RepoA" Result : fatal: destination path 'ssh://luc@EERSTENASDS119J/volume1/RepoA' already exists and is not an empty directory.

The system created a directory ssh://luc@EERSTENASDS119J/volume1/RepoA in my current path.

So git clone did not interpret the URL specification. Used the workaround of Alec.

Description Box using "onmouseover"

Assuming popup is the ID of your "description box":

HTML

<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>

JavaScript

var e = document.getElementById('parent');
e.onmouseover = function() {
  document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
  document.getElementById('popup').style.display = 'none';
}

Alternatively you can get rid of JavaScript entirely and do it just with CSS:

CSS

#parent #popup {
  display: none;
}

#parent:hover #popup {
  display: block;
}

python and sys.argv

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

Print to standard printer from Python?

This has only been tested on Windows:

You can do the following:

import os

os.startfile("C:/Users/TestFile.txt", "print")

This will start the file, in its default opener, with the verb 'print', which will print to your default printer.Only requires the os module which comes with the standard library

detect back button click in browser

Please try this (if the browser does not support "onbeforeunload"):

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

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});

How can I manually generate a .pyc file from a .py file

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How to export data with Oracle SQL Developer?

To export data you need to right click on your results and select export data, after which you will be asked for a specific file format such as insert, loader, or text etc. After selecting this browse your directory and select the export destination.

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

How can I retrieve a table from stored procedure to a datatable?

Explaining if any one want to send some parameters while calling stored procedure as below,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }

How do you get a string from a MemoryStream?

use a StreamReader, then you can use the ReadToEnd method that returns a string.

Java: random long number in 0 <= x < n range

From Java 8 API

It could be easier to take actual implementation from API doc https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#longs-long-long-long- they are using it to generate longs stream. And your origin can be "0" like in the question.

long nextLong(long origin, long bound) {
  long r = nextLong();
  long n = bound - origin, m = n - 1;
  if ((n & m) == 0L)  // power of two
    r = (r & m) + origin;
  else if (n > 0L) {  // reject over-represented candidates
    for (long u = r >>> 1;            // ensure nonnegative
         u + m - (r = u % n) < 0L;    // rejection check
         u = nextLong() >>> 1) // retry
        ;
    r += origin;
  }
  else {              // range not representable as long
    while (r < origin || r >= bound)
      r = nextLong();
  }
  return r;
}

Run function from the command line

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

Tomcat 7 is not running on browser(http://localhost:8080/ )

You can run below commands.

 ./catalina.sh run

Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

how to convert java string to Date object

    try 
    {  
      String datestr="06/27/2007";
      DateFormat formatter; 
      Date date; 
      formatter = new SimpleDateFormat("MM/dd/yyyy");
      date = (Date)formatter.parse(datestr);  
    } 
    catch (Exception e)
    {}

month is MM, minutes is mm..

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Return multiple values from a SQL Server function

Change it to a table-valued function

Please refer to the following link, for example.

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

Black transparent overlay on image hover with only CSS?

I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img elements, you would still need to wrap the img element though.

LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT

<div class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

As for the CSS, set optional dimensions on the .image element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img element itself, see.

.image {
    position: relative;
    width: 400px;
    height: 400px;
}

Give the child img element a width of 100% of the parent and add vertical-align:top to fix the default baseline alignment issues.

.image img {
    width: 100%;
    vertical-align: top;
}

As for the pseudo element, set a content value and absolutely position it relative to the .image element. A width/height of 100% will ensure that this works with varying img dimensions. If you want to transition the element, set an opacity of 0 and add the transition properties/values.

.image:after {
    content: '\A';
    position: absolute;
    width: 100%; height:100%;
    top:0; left:0;
    background:rgba(0,0,0,0.6);
    opacity: 0;
    transition: all 1s;
    -webkit-transition: all 1s;
}

Use an opacity of 1 when hovering over the pseudo element in order to facilitate the transition:

.image:hover:after {
    opacity: 1;
}

END RESULT HERE


If you want to add text on hover:

For the simplest approach, just add the text as the pseudo element's content value:

EXAMPLE HERE

.image:after {
    content: 'Here is some text..';
    color: #fff;

    /* Other styling.. */
}

That should work in most instances; however, if you have more than one img element, you might not want the same text to appear on hover. You could therefore set the text in a data-* attribute and therefore have unique text for every img element.

EXAMPLE HERE

.image:after {
    content: attr(data-content);
    color: #fff;
}

With a content value of attr(data-content), the pseudo element adds the text from the .image element's data-content attribute:

<div data-content="Text added on hover" class="image">
    <img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>

You can add some styling and do something like this:

EXAMPLE HERE

In the above example, the :after pseudo element serves as the black overlay, while the :before pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.

.image:after, .image:before {
    position: absolute;
    opacity: 0;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
}
.image:after {
    content: '\A';
    width: 100%; height:100%;
    top: 0; left:0;
    background:rgba(0,0,0,0.6);
}
.image:before {
    content: attr(data-content);
    width: 100%;
    color: #fff;
    z-index: 1;
    bottom: 0;
    padding: 4px 10px;
    text-align: center;
    background: #f00;
    box-sizing: border-box;
    -moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
    opacity: 1;
}

File Not Found when running PHP with Nginx

I just spent like 40 minutes trying to debug a non-working /status with:

$ SCRIPT_NAME=/status SCRIPT_FILENAME=/status QUERY_STRING= REQUEST_METHOD=GET cgi-fcgi -bind -connect /var/run/php5-fpm.sock

It just produced "File not found" error, while the actual scripts (that are found on the filesystem) worked just fine.

Turned out, I had a couple of orphaned processes of php5-fpm. After I killed everything and restarted php5-fpm cleanly, it just went back to normal.

Hope this helps.

Is there a unique Android device ID?

There’s rather useful info here.

It covers five different ID types:

  1. IMEI (only for Android devices with Phone use; needs android.permission.READ_PHONE_STATE)
  2. Pseudo-Unique ID (for all Android devices)
  3. Android ID (can be null, can change upon factory reset, can be altered on rooted phone)
  4. WLAN MAC Address string (needs android.permission.ACCESS_WIFI_STATE)
  5. BT MAC Address string (devices with Bluetooth, needs android.permission.BLUETOOTH)

How to generate a random number between 0 and 1?

Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?

As noted in another comment, SA() isn't returning anything explicitly.

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]

Convert PEM to PPK file format

PuTTYgen for Ubuntu/Linux and PEM to PPK

sudo apt install putty-tools
puttygen -t rsa -b 2048 -C "user@host" -o keyfile.ppk

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

How to have EditText with border in Android Lollipop

Write editTextBackground.xml in drawable folder in resources

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="@color/borderColor" />
</shape>

don't forget to declare color in resources named borderColor.

and assign this background to the EditText in xml background attribute

<EditText
    android:id="@+id/text"
    android:background="@drawable/editTextBackground"
    />

and it'll set border to EditText.

UPDATE

You can change border of edit text without drawable by using style attribute

style="@style/Widget.AppCompat.EditText"

for more details visit customize edit text

How can I mark a foreign key constraint using Hibernate annotations?

There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.

The following works for a non-primary key mapping as well.

Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:

@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;

Enter image description here

@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;

How ViewBag in ASP.NET MVC works

ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

It is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();

which is why you can do :

ViewBag.Foo = "Bar";

A Sample Expander Object Code:

public class ExpanderObject : DynamicObject, IDynamicMetaObjectProvider
{
    public Dictionary<string, object> objectDictionary;

    public ExpanderObject()
    {
        objectDictionary = new Dictionary<string, object>();
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        object val;
        if (objectDictionary.TryGetValue(binder.Name, out val))
        {
            result = val;
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        try
        {
            objectDictionary[binder.Name] = value;
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

Android: Color To Int conversion

Any color parse into int simplest two way here:

1) Get System Color

int redColorValue = Color.RED;

2) Any Color Hex Code as a String Argument

int greenColorValue = Color.parseColor("#00ff00")

MUST REMEMBER in above code Color class must be android.graphics...!

response.sendRedirect() from Servlet to JSP does not seem to work

You can use this:

response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));

The last part is your path in your web-app

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

How can I open Windows Explorer to a certain directory from within a WPF app?

You can use System.Diagnostics.Process.Start.

Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.

public partial class Window1 : Window
{
    public Window1()
    {
        ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
        InitializeComponent();
    }

    public enum ShowCommands : int
    {
        SW_HIDE = 0,
        SW_SHOWNORMAL = 1,
        SW_NORMAL = 1,
        SW_SHOWMINIMIZED = 2,
        SW_SHOWMAXIMIZED = 3,
        SW_MAXIMIZE = 3,
        SW_SHOWNOACTIVATE = 4,
        SW_SHOW = 5,
        SW_MINIMIZE = 6,
        SW_SHOWMINNOACTIVE = 7,
        SW_SHOWNA = 8,
        SW_RESTORE = 9,
        SW_SHOWDEFAULT = 10,
        SW_FORCEMINIMIZE = 11,
        SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(
        IntPtr hwnd,
        string lpOperation,
        string lpFile,
        string lpParameters,
        string lpDirectory,
        ShowCommands nShowCmd);
}

The declarations come from the pinvoke.net website.

Windows command prompt log to a file

First method

For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.

Steps:

  1. type PowerShell in search area and click on "Windows PowerShell"

  2. If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)

  3. run the .bat file with following command

    PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt

This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.

Second method

You can use file redirection (>, >>) as suggest by Bali C above.

I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.

How to select a single column with Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column.

Move branch pointer to different commit without checkout

Honestly, I'm surprised how nobody thought about the git push command:

git push -f . <destination>:<branch>

The dot ( . ) refers the local repository, and you may need the -f option because the destination could be "behind its remote counterpart".

Although this command is used to save your changes in your server, the result is exactly the same as if moving the remote branch (<branch>) to the same commit as the local branch (<destination>)

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

static void init_random(uint32_t initseed=0)
{
    if (initseed==0)
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
    }
    else
        seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
    //seed=42
    //SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
    initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}

If the following code lines not run in the run-time:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:

In file included from ../../shogun/features/SubsetStack.h:14:0, 
                 from ../../shogun/features/Features.h:21, 
                 from ../../shogun/ui/SGInterface.h:7, 
                 from MatlabInterface.h:15, 
                 from matlabInterface.cpp:7: 
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)': 
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope

Get the current file name in gulp.src()

Here is another simple way.

var es, log, logFile;

es = require('event-stream');

log = require('gulp-util').log;

logFile = function(es) {
  return es.map(function(file, cb) {
    log(file.path);
    return cb();
  });
};

gulp.task("do", function() {
 return gulp.src('./examples/*.html')
   .pipe(logFile(es))
   .pipe(gulp.dest('./build'));
});

How can I remove a commit on GitHub?

In case you like to keep the commit changes after deletion:

Note that this solution works if the commit to be removed is the last committed one.


1 - Copy the commit reference you like to go back to from the log:

git log

2 - Reset git to the commit reference:

 git reset <commit_ref>

3 - Stash/store the local changes from the wrong commit to use later after pushing to remote:

 git stash

4 - Push the changes to remote repository, (-f or --force):

git push -f

5 - Get back the stored changes to local repository:

git stash apply

7 - In case you have untracked/new files in the changes, you need to add them to git before committing:

git add .

6 - Add whatever extra changes you need, then commit the needed files, (or use a dot '.' instead of stating each file name, to commit all files in the local repository:

git commit -m "<new_commit_message>" <file1> <file2> ...

or

git commit -m "<new_commit_message>" .

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

<input type="file" name="file" id="file">

Remember to put your javascript code after the file field is rendered.

WCF Service , how to increase the timeout?

Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.

WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();

or

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    //More codes here 
}

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

In Windows, like this:

-Djava.library.path="C:/MyLibPath;%PATH%"

%PATH% is your old -Djava.library.path

Is this how you define a function in jQuery?

No, you can just write the function as:

$(document).ready(function() {
    MyBlah("hello");
});

function MyBlah(blah) {
    alert(blah);
}

This calls the function MyBlah on content ready.

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

Posting JSON Data to ASP.NET MVC

In MVC3 they've added this.

But whats even more nice is that since MVC source code is open you can grab the ValueProvider and use it yourself in your own code (if youre not on MVC3 yet).

You will end up with something like this

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())

jsPDF multi page PDF with HTML renderer

You can use html2canvas plugin and jsPDF both. Process order: html to png & png to pdf

Example code:

jQuery('#part1').html2canvas({
    onrendered: function( canvas ) {
        var img1 = canvas.toDataURL('image/png');
    }
});
jQuery('#part2').html2canvas({
    onrendered: function( canvas ) {
        var img2 = canvas.toDataURL('image/png');
    }
});
jQuery('#part3').html2canvas({
    onrendered: function( canvas ) {
        var img3 = canvas.toDataURL('image/png');
    }
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page

doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");

Chrome hangs after certain amount of data transfered - waiting for available socket

Explanation:

This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video> or <audio> tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.

Solution 1:

You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto".

Solution 2:

If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.

Solution 3: Force-open Sockets (Not recommended)

If you must, you can force-open the sockets in your browser (In Chrome only):

  1. Go to the address bar and type chrome://net-internals.
  2. Select Sockets from the menu.
  3. Click on the Flush socket pools button.

This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

If someone would need a one liner:

iwr -Uri 'https://api.github.com/user' -Headers @{ Authorization = "Basic "+ [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("user:pass")) }

SaveFileDialog setting default path and file type?

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

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

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

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

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

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

Defining TypeScript callback type

You can use the following:

  1. Type Alias (using type keyword, aliasing a function literal)
  2. Interface
  3. Function Literal

Here is an example of how to use them:

type myCallbackType = (arg1: string, arg2: boolean) => number;

interface myCallbackInterface { (arg1: string, arg2: boolean): number };

class CallbackTest
{
    // ...

    public myCallback2: myCallbackType;
    public myCallback3: myCallbackInterface;
    public myCallback1: (arg1: string, arg2: boolean) => number;

    // ...

}

jQuery .val() vs .attr("value")

I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Where does Internet Explorer store saved passwords?

I found the answer. IE stores passwords in two different locations based on the password type:

  • Http-Auth: %APPDATA%\Microsoft\Credentials, in encrypted files
  • Form-based: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2, encrypted with the url

From a very good page on NirSoft.com:

Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:

  • AutoComplete Passwords: These passwords are saved in the following location in the Registry: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2 The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).

  • HTTP Authentication Passwords: These passwords are stored in the Credentials file under Documents and Settings\Application Data\Microsoft\Credentials, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.

In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead/CredWrite, where the user can manage their passwords from within an established UI system in Windows.

Why is Tkinter Entry's get function returning nothing?

It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.

Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        print(self.entry.get())

app = SampleApp()
app.mainloop()

Run the program, type into the entry widget, then click on the button.

Linq where clause compare only date value without time value

Try this,

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
         && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x.DateTimeValueColumn)
    .AsEnumerable()
    .select(p=>p.DateTimeValueColumn.value.toString("YYYY-MMM-dd");

What is the most efficient way to deep clone an object in JavaScript?

Shallow copy one-liner (ECMAScript 5th edition):

var origin = { foo : {} };
var copy = Object.keys(origin).reduce(function(c,k){c[k]=origin[k];return c;},{});

console.log(origin, copy);
console.log(origin == copy); // false
console.log(origin.foo == copy.foo); // true

And shallow copy one-liner (ECMAScript 6th edition, 2015):

var origin = { foo : {} };
var copy = Object.assign({}, origin);

console.log(origin, copy);
console.log(origin == copy); // false
console.log(origin.foo == copy.foo); // true

How to create radio buttons and checkbox in swift (iOS)?

Though some of the answers mention it rightly that we can use the Selected State to set an image for Selected state of the button, it won't work elegantly when the button has to have both image and text.

Like many, I ended by subclassing UIButton; however, added support for setting images from Interface Builder.

Below is my code:

import UIKit

class CustomCheckbox: UIButton {

    @IBInspectable var defaultStateImage: UIImage? = nil {
        didSet{
            self.setNeedsDisplay()
        }
    }

    @IBInspectable var selectedStateImage: UIImage? = nil {
        didSet{
            self.setNeedsDisplay()
        }
    }

    @IBInspectable var gapPadding: CGFloat = 0 {
        didSet{
            self.setNeedsDisplay()
        }
    }

    @IBInspectable var isChecked: Bool = false {
        didSet{
            self.setNeedsDisplay()
        }
    }

    var defaultImageView: UIImageView? = nil
    var selectedImageView: UIImageView? = nil

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setup()
    }

    func setup() {
        if(defaultStateImage != nil) {
            defaultImageView = UIImageView(image: defaultStateImage)
            defaultImageView?.translatesAutoresizingMaskIntoConstraints = false

            addSubview(defaultImageView!)

            let length = CGFloat(16)
            titleEdgeInsets.left += length

            NSLayoutConstraint.activate([
                defaultImageView!.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: -gapPadding),
                defaultImageView!.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
                defaultImageView!.widthAnchor.constraint(equalToConstant: length),
                defaultImageView!.heightAnchor.constraint(equalToConstant: length)
            ])
        }

        if(selectedStateImage != nil) {
            selectedImageView = UIImageView(image: selectedStateImage)
            selectedImageView!.translatesAutoresizingMaskIntoConstraints = false

            addSubview(selectedImageView!)

            let length = CGFloat(16)
            titleEdgeInsets.left += length

            NSLayoutConstraint.activate([
                selectedImageView!.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: -gapPadding),
                selectedImageView!.centerYAnchor.constraint(equalTo: self.titleLabel!.centerYAnchor, constant: 0),
                selectedImageView!.widthAnchor.constraint(equalToConstant: length),
                selectedImageView!.heightAnchor.constraint(equalToConstant: length)
            ])
        }

        if defaultImageView != nil {
            defaultImageView!.isHidden = isChecked
        }

        if selectedImageView != nil  {
            selectedImageView!.isHidden = !isChecked
        }

        self.addTarget(self, action: #selector(checkChanged(_:)), for: .touchUpInside)
    }

    @objc func checkChanged(_ btn : UIButton){
        self.isChecked = !self.isChecked

        if defaultImageView != nil {
            defaultImageView!.isHidden = isChecked
        }

        if selectedImageView != nil  {
            selectedImageView!.isHidden = !isChecked
        }
    }
}

How to escape special characters of a string with single backslashes

re.escape doesn't double escape. It just looks like it does if you run in the repl. The second layer of escaping is caused by outputting to the screen.

When using the repl, try using print to see what is really in the string.

$ python
>>> import re
>>> re.escape("\^stack\.\*/overflo\\w\$arr=1")
'\\\\\\^stack\\\\\\.\\\\\\*\\/overflo\\\\w\\\\\\$arr\\=1'
>>> print re.escape("\^stack\.\*/overflo\\w\$arr=1")
\\\^stack\\\.\\\*\/overflo\\w\\\$arr\=1
>>>

Create Git branch with current changes

Since you haven't made any commits yet, you can save all your changes to the stash, create and switch to a new branch, then pop those changes back into your working tree:

git stash  # save local modifications to new stash
git checkout -b topic/newbranch
git stash pop  # apply stash and remove it from the stash list

docker unauthorized: authentication required - upon push with successful login

If you are pushing a new private image for the first time, make sure your subscription supports this extra image.

Docker allows you to have 6 private images named, even if you only pay for 5, but not to push that 6th image. The lack of an informative message is confusing and irritating.

Quick Sort Vs Merge Sort

In addition to the others: Merge sort is very efficient for immutable datastructures like linked lists and is therefore a good choice for (purely) functional programming languages.

A poorly implemented quicksort can be a security risk.

Error after upgrading pip: cannot import name 'main'

I have the same problem and solved it. Here is my solution. First, when I run pip install something, the error came out like this:

Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'

So, I cd into the file /usr/bin/ and cat pip3 to see the code in it. I see this in it:

#!/usr/bin/python3
# GENERATED BY DEBIAN
import sys
# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.
from pip import main
if __name__ == '__main__':
    sys.exit(main())

And then I think that it was not in the installation path. So I cd into the python3-pip, like this:

cd /.local/lib/python3.5/site-packages/pip

P.S.: you have to cd into the right directions in your computer Then I cat the file to see the differences(you can use other operations to see the code):

cat __main__.py

And I saw this:

from __future__ import absolute_import
import os
import sys
# If we are running from a wheel, add the wheel to sys.path
# This allows the usage python pip-*.whl/pip install pip-*.whl
if __package__ == '':
    # __file__ is pip-*.whl/pip/__main__.py
    # first dirname call strips of '/__main__.py', second strips off '/pip'
    # Resulting path is the name of the wheel itself
    # Add that to sys.path so we can import pip
    path = os.path.dirname(os.path.dirname(__file__))
    sys.path.insert(0, path)

from pip._internal import main as _main  # isort:skip # noqa

if __name__ == '__main__':
    sys.exit(_main())

So, can you see the difference? I can figure out that I have to make the file the same as the file in /usr/bin/pip3

So, I copied the code in /.local/lib/python3.5/site-packages/pip to replace the code in /usr/bin/pip3 and the problem disappear!

P.S.: pip3 or pip have no difference in this problem. I will be happy if my solution solve your problem!

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

Python time measure function

Timeit has two big flaws: it doesn't return the return value of the function, and it uses eval, which requires passing in extra setup code for imports. This solves both problems simply and elegantly:

def timed(f):
  start = time.time()
  ret = f()
  elapsed = time.time() - start
  return ret, elapsed

timed(lambda: database.foo.execute('select count(*) from source.apachelog'))
(<sqlalchemy.engine.result.ResultProxy object at 0x7fd6c20fc690>, 4.07547402381897)

Render HTML to an image

I know this is quite an old question which already has a lot of answers, yet I still spent hours trying to actually do what I wanted:

  • given an html file, generate a (png) image with transparent background from the command line

Using Chrome headless (version 74.0.3729.157 as of this response), it is actually easy:

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless --screenshot --window-size=256,256 --default-background-color=0 button.html

Explanation of the command:

  • you run Chrome from the command line (here shown for the Mac, but assuming similar on Windows or Linux)
  • --headless runs Chrome without opening it and exits after the command completes
  • --screenshot will capture a screenshot (note that it generates a file called screenshot.png in the folder where the command is run)
  • --window-size allow to only capture a portion of the screen (format is --window-size=width,height)
  • --default-background-color=0 is the magic trick that tells Chrome to use a transparent background, not the default white color
  • finally you provide the html file (as a url either local or remote...)

How to validate an e-mail address in swift?

If you are looking for a clean and simple solution to do this, you should take a look at https://github.com/nsagora/validation-components.

It contains an email validation predicate which is easy integrate in your code:

let email = "[email protected]"
let rule = EmailValidationPredicate()
let isValidEmail = rule.evaluate(with: email)

Behind the hood it uses the RFC 5322 reg ex (http://emailregex.com):

let regex = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
    "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
    "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
    "z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
    "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
    "9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
    "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"

How do I get a PHP class constructor to call its parent's parent's constructor?

// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {
        $this->___construct();
    }

    protected function ___construct()
    {
        // grandpa's logic
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        parent::___construct();
    }
}

note that "___construct" is not some magic name, you can call it "doGrandpaStuff".

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

How do I check particular attributes exist or not in XML?

EDIT

Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.

END EDIT

You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.

foreach (XmlNode xNode in nodeListName)
{
    if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
    {
         parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

XmlAttributeCollection.ItemOf Property (String)

Add a row number to result set of a SQL query

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

Stateless vs Stateful

Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...

HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...

Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...

Woocommerce get products

<?php
$args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args ); 
?>

This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

Maximum concurrent Socket.IO connections

This guy appears to have succeeded in having over 1 million concurrent connections on a single Node.js server.

http://blog.caustik.com/2012/08/19/node-js-w1m-concurrent-connections/

It's not clear to me exactly how many ports he was using though.

Add button to navigationbar programmatically

Simple use native editBarButton like this

self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.navigationItem.rightBarButtonItem setAction:@selector(editBarBtnPressed)];

and then

- (void)editBarBtnPressed {
    if ([infoTable isEditing]) {
        [self.editButtonItem setTitle:@"Edit"];
        [infoTable setEditing:NO animated:YES];
    }
    else {
        [self.editButtonItem setTitle:@"Done"];
        [infoTable setEditing:YES animated:YES];
    }
}

Have fun...!!!

Calculate distance between two points in google maps V3

Example using GPS latitude/longitude of 2 points.

var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;

var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));       

Printing all global variables/local variables?

In addition, since info locals does not display the arguments to the function you're in, use

(gdb) info args

For example:

int main(int argc, char *argv[]) {
    argc = 6*7;    //Break here.
    return 0;
}

argc and argv won't be shown by info locals. The message will be "No locals."

Reference: info locals command.

Window.open as modal popup?

You can try open a modal dialog with html5 and css3, try this code:

_x000D_
_x000D_
.windowModal {_x000D_
    position: fixed;_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    background: rgba(0,0,0,0.8);_x000D_
    z-index: 99999;_x000D_
    opacity:0;_x000D_
    -webkit-transition: opacity 400ms ease-in;_x000D_
    -moz-transition: opacity 400ms ease-in;_x000D_
    transition: opacity 400ms ease-in;_x000D_
    pointer-events: none;_x000D_
}_x000D_
.windowModal:target {_x000D_
    opacity:1;_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
.windowModal > div {_x000D_
    width: 400px;_x000D_
    position: relative;_x000D_
    margin: 10% auto;_x000D_
    padding: 5px 20px 13px 20px;_x000D_
    border-radius: 10px;_x000D_
    background: #fff;_x000D_
    background: -moz-linear-gradient(#fff, #999);_x000D_
    background: -webkit-linear-gradient(#fff, #999);_x000D_
    background: -o-linear-gradient(#fff, #999);_x000D_
}_x000D_
.close {_x000D_
    background: #606061;_x000D_
    color: #FFFFFF;_x000D_
    line-height: 25px;_x000D_
    position: absolute;_x000D_
    right: -12px;_x000D_
    text-align: center;_x000D_
    top: -10px;_x000D_
    width: 24px;_x000D_
    text-decoration: none;_x000D_
    font-weight: bold;_x000D_
    -webkit-border-radius: 12px;_x000D_
    -moz-border-radius: 12px;_x000D_
    border-radius: 12px;_x000D_
    -moz-box-shadow: 1px 1px 3px #000;_x000D_
    -webkit-box-shadow: 1px 1px 3px #000;_x000D_
    box-shadow: 1px 1px 3px #000;_x000D_
}_x000D_
_x000D_
.close:hover { background: #00d9ff; }
_x000D_
<a href="#divModal">Open Modal Window</a>_x000D_
_x000D_
<div id="divModal" class="windowModal">_x000D_
    <div>_x000D_
        <a href="#close" title="Close" class="close">X</a>_x000D_
        <h2>Modal Dialog</h2>_x000D_
        <p>This example shows a modal window without using javascript only using html5 and css3, I try it it¡</p>_x000D_
        <p>Using javascript, with new versions of html5 and css3 is not necessary can do whatever we want without using js libraries.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you run JavaScript script through the Terminal?

If you're using MacBook.

  1. Set up node.js in your system and open up the terminal
  2. Navigate to the directory, where the js file is saved.
  3. To execute run node <filename.js>

example, if filename is script.js run node script.js

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).

EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.

How to convert a full date to a short date in javascript?

I was able to do that with :

var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))

the 04/04/2013 is just for testing, replace with your Date Object.

Presenting a UIAlertController properly on an iPad using iOS 8

You can present a UIAlertController from a popover by using UIPopoverPresentationController.

In Obj-C:

UIViewController *self; // code assumes you're in a view controller
UIButton *button; // the button you want to show the popup sheet from

UIAlertController *alertController;
UIAlertAction *destroyAction;
UIAlertAction *otherAction;

alertController = [UIAlertController alertControllerWithTitle:nil
                                                      message:nil
                           preferredStyle:UIAlertControllerStyleActionSheet];
destroyAction = [UIAlertAction actionWithTitle:@"Remove All Data"
                                         style:UIAlertActionStyleDestructive
                                       handler:^(UIAlertAction *action) {
                                           // do destructive stuff here
                                       }];
otherAction = [UIAlertAction actionWithTitle:@"Blah"
                                       style:UIAlertActionStyleDefault
                                     handler:^(UIAlertAction *action) {
                                         // do something here
                                     }];
// note: you can control the order buttons are shown, unlike UIActionSheet
[alertController addAction:destroyAction];
[alertController addAction:otherAction];
[alertController setModalPresentationStyle:UIModalPresentationPopover];

UIPopoverPresentationController *popPresenter = [alertController 
                                              popoverPresentationController];
popPresenter.sourceView = button;
popPresenter.sourceRect = button.bounds;
[self presentViewController:alertController animated:YES completion:nil];

Editing for Swift 4.2, though there are many blogs available for the same but it may save your time to go and search for them.

if let popoverController = yourAlert.popoverPresentationController {
    popoverController.sourceView = self.view //to set the source of your alert
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // you can set this as per your requirement.
    popoverController.permittedArrowDirections = [] //to hide the arrow of any particular direction
}

jQuery - get all divs inside a div with class ".container"

To get all divs under 'container', use the following:

$(".container>div")  //or
$(".container").children("div");

You can stipulate a specific #id instead of div to get a particular one.

You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:

$(".container>div[id=]")

React Error: Target Container is not a DOM Element

For those that implemented react js in some part of the website and encounter this issue. Just add a condition to check if the element exist on that page before you render the react component.

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

Calculate logarithm in python

math.log10(1.5)

Use the log10 function in the math module.

How to identify all stored procedures referring a particular table

SELECT
    o.name
FROM
    sys.sql_modules sm
INNER JOIN sys.objects o ON
    o.object_id = sm.object_id
WHERE
    sm.definition LIKE '%<table name>%'

Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.

How can I check if an InputStream is empty without reading from it?

Without reading you can't do this. But you can use a work around like below.

You can use mark() and reset() methods to do this.

mark(int readlimit) method marks the current position in this input stream.

reset() method repositions this stream to the position at the time the mark method was last called on this input stream.

Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.

To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.

    if (inputStream.markSupported()) {
          inputStream.mark(0);
          if (inputStream.read() != -1) {
               inputStream.reset();
          } else {
               //Inputstream is empty
          }
    }

Here if the input stream is empty then read() method will return -1.

How to load image files with webpack file-loader

Alternatively you can write the same like

{
    test: /\.(svg|png|jpg|jpeg|gif)$/,
    include: 'path of input image directory',
    use: {
        loader: 'file-loader',
        options: {
            name: '[path][name].[ext]',
            outputPath: 'path of output image directory'
        }
    }
}

and then use simple import

import varName from 'relative path';

and in jsx write like <img src={varName} ..../>

.... are for other image attributes

How to prevent multiple definitions in C?

If you have added test.c to your Code::Blocks project, the definition will be seen twice - once via the #include and once by the linker. You need to:

  • remove the #include "test.c"
  • create a file test.h which contains the declaration: void test();
  • include the file test.h in main.c

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Following configuration, you need to set:

To open the port 5432 edit your /etc/postgresql/9.1/main/postgresql.conf and change

# Connection Settings -

listen_addresses = '*'          # what IP address(es) to listen on;

In /etc/postgresql/10/main/pg_hba.conf

# IPv4 local connections:
host    all             all             0.0.0.0/0           md5

Now restart your DBMS

sudo service postgresql restart

Now you can connect with

psql -h hostname(IP) -p port -U username -d database

How do I address unchecked cast warnings?

Here's one way I handle this when I override the equals() operation.

public abstract class Section<T extends Section> extends Element<Section<T>> {
    Object attr1;

    /**
    * Compare one section object to another.
    *
    * @param obj the object being compared with this section object
    * @return true if this section and the other section are of the same
    * sub-class of section and their component fields are the same, false
    * otherwise
    */       
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            // this exists, but obj doesn't, so they can't be equal!
            return false;
        }

        // prepare to cast...
        Section<?> other;

        if (getClass() != obj.getClass()) {
            // looks like we're comparing apples to oranges
            return false;
        } else {
            // it must be safe to make that cast!
            other = (Section<?>) obj;
        }

        // and then I compare attributes between this and other
        return this.attr1.equals(other.attr1);
    }
}

This seems to work in Java 8 (even compiled with -Xlint:unchecked)

Push local Git repo to new remote including all branches and tags

I found above answers still have some unclear things, which will mislead users. First, It's sure that git push new_origin --all and git push new_origin --mirror can't duplicate all branches of origin, it just duplicate your local existed branches to your new_origin.

Below is two useful methods I have tested:

1,duplicate by clone bare repo.git clone --bare origin_url, then enter the folder, and git push new_origin_url --mirror.By this way, you can also use git clone --mirror origin_url, both --bareand --mirror will download a bare repo,not including workspace. please refer this

2,If you have a git repo by using git clone, which means you have bare repo and git workspace, you can use git remote add new_origin new_origin_url, and then git push new_origin +refs/remotes/origin/\*:refs/heads/\*,and then git push new_origin --tags

By this way, you will get a extra head branch, which make no sense.

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

TypeError: 'int' object is not callable

In my case I changed:

return <variable>

with:

return str(<variable>)

try with the following and it must work:

str(round((a/b)*0.9*c))

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

JQuery - Set Attribute value

Some things before the actual code..

the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..

so the code would be

$("input:checkbox[name='chk0']").removeAttr('disabled');

Bringing the answer up-to-date

You should use the .prop() method (added since v1.6)

$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox

and

$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox

Set the maximum character length of a UITextField

While the UITextField class has no max length property, it's relatively simple to get this functionality by setting the text field's delegate and implementing the following delegate method:

Objective-C

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // Prevent crashing undo bug – see note below.
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }
        
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return newLength <= 25;
}

Swift

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    let currentCharacterCount = textField.text?.count ?? 0
    if range.length + range.location > currentCharacterCount {
        return false
    }
    let newLength = currentCharacterCount + string.count - range.length
    return newLength <= 25
}

Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it's current length and the string length we're inserting (either through pasting copied text or typing a single character using the keyboard), minus the range length. If this value is too long (more than 25 characters in this example), return NO to prohibit the change.

When typing in a single character at the end of a text field, the range.location will be the current field's length, and range.length will be 0 because we're not replacing/deleting anything. Inserting into the middle of a text field just means a different range.location, and pasting multiple characters just means string has more than one character in it.

Deleting single characters or cutting multiple characters is specified by a range with a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.

A note on the crashing "undo" bug

As is mentioned in the comments, there is a bug with UITextField that can lead to a crash.

If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application's undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the UITextField will attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn't exist.

Fortunately you can protect the UITextField from killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.

swift 3.0 with copy and paste working fine.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let str = (textView.text + text)
        if str.characters.count <= 10 {
            return true
        }
        textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 10))
        return false
    }

Hope it's helpful to you.

array of string with unknown size

If you want to use array without knowing the size first you have to declare it and later you can instantiate it like

string[] myArray;
...
...
myArray=new string[someItems.count];

Hide/Show components in react native

The following example is coding in typescript with Hooks.

import React, { useState, useEffect } from "react";

........

const App = () => {

   const [showScrollView, setShowScrollView] = useState(false);

   ......

   const onPress = () => {
    // toggle true or false
    setShowScrollView(!showScrollView);
  }

  ......

      </MapboxGL.ShapeSource>
        <View>{showScrollView ? (<DetailsScrollView />) : null}</View>
      </MapboxGL.MapView>
  ......

}

How do I increase the capacity of the Eclipse output console?

On the MAC OS X 10.9.5 and Eclipse Luna Service Release 1 (4.4.1), its not found under the Window menu, but instead under: Eclipse > Preferences > Run/Debug > Console.

Better way to find last used row

You should use a with statement to qualify both your Rows and Columns counts. This will prevent any errors while working with older pre 2007 and newer 2007 Excel Workbooks.

Last Column

With Sheets("Sheet2")
    .Cells(1, .Columns.Count).End(xlToLeft).Column
End With 

Last Row

With Sheets("Sheet2")
    .Range("A" & .Rows.Count).End(xlUp).Row
End With 

Or

With Sheets("Sheet2")
    .Cells(.Rows.Count, 1).End(xlUp).Row
End With 

How do I clear/delete the current line in terminal?

I have the complete shortcuts list:

  1. Ctrl+a Move cursor to start of line
  2. Ctrl+e Move cursor to end of line
  3. Ctrl+b Move back one character
  4. Alt+b Move back one word
  5. Ctrl+f Move forward one character
  6. Alt+f Move forward one word
  7. Ctrl+d Delete current character
  8. Ctrl+w Cut the last word
  9. Ctrl+k Cut everything after the cursor
  10. Alt+d Cut word after the cursor
  11. Alt+w Cut word before the cursor
  12. Ctrl+y Paste the last deleted command
  13. Ctrl+_ Undo
  14. Ctrl+u Cut everything before the cursor
  15. Ctrl+xx Toggle between first and current position
  16. Ctrl+l Clear the terminal
  17. Ctrl+c Cancel the command
  18. Ctrl+r Search command in history - type the search term
  19. Ctrl+j End the search at current history entry
  20. Ctrl+g Cancel the search and restore original line
  21. Ctrl+n Next command from the History
  22. Ctrl+p previous command from the History

Regex: Specify "space or start of string" and "space or end of string"

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

Getting reference to child component in parent component

You can use ViewChild

<child-tag #varName></child-tag>

@ViewChild('varName') someElement;

ngAfterViewInit() {
  someElement...
}

where varName is a template variable added to the element. Alternatively, you can query by component or directive type.

There are alternatives like ViewChildren, ContentChild, ContentChildren.

@ViewChildren can also be used in the constructor.

constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)

The advantage is that the result is available earlier.

See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.

Note: @Query() is the deprecated predecessor of @ContentChildren()

Update

Query is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145

How can I resize an image dynamically with CSS as the browser width/height changes?

Just use this code. What most are forgeting is to specify max-width as the max-width of the image

img {   
    height: auto;
    width: 100%;
    max-width: 300px;
}

Check this demonstration http://shorturl.at/nBKVY

How to find all links / pages on a website

Check out linkchecker—it will crawl the site (while obeying robots.txt) and generate a report. From there, you can script up a solution for creating the directory tree.

Uninstall Eclipse under OSX?

Deleting the eclipse folder is equivalent to uninstalling it. In fact, if you don't want to tamper with the existing installation you can create another instance of eclipse and run from the new location.

How do I get current scope dom-element in AngularJS controller?

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

Convert JavaScript String to be all lower case?

Simply use JS toLowerCase()
let v = "Your Name" let u = v.toLowerCase(); or
let u = "Your Name".toLowerCase();

Remove spacing between table cells and rows

If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like

table {
      border-collapse: separate;
      white-space: normal;
      line-height: normal;
      font-weight: normal;
      font-size: medium;
      font-style: normal;
      color: -internal-quirk-inherit;
      text-align: start;
      border-spacing: 0px!important;
      font-variant: normal;   }

It saved my day.Hope it would be of help. Thanks.

How to read values from the querystring with ASP.NET Core?

  1. Startup.cs add this service services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  2. Your view add inject @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
  3. get your value

Code

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    var id = HttpContextAccessor.HttpContext.Request.RouteValues["id"];

    if (id != null)
    {
        // parameter exist in your URL 
    }

    string navigation = await Navigation.WebNavigation(activeTab);
}

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

How to generate Javadoc from command line

Let's say you have the following directory structure where you want to generate javadocs on file1.java and file2.java (package com.test), with the javadocs being placed in C:\javadoc\test:

C:\
|
+--javadoc\
|  |
|  +--test\
|
+--projects\
   |
   +--com\
      |
      +--test\
         |
         +--file1.java
         +--file2.java

In the command terminal, navigate to the root of your package: C:\projects. If you just want to generate the standard javadocs on all the java files inside the project, run the following command (for multiple packages, separate the package names by spaces):

C:\projects> javadoc -d [path to javadoc destination directory] [package name]

C:\projects> javadoc -d C:\javadoc\test com.test

If you want to run javadocs from elsewhere, you'll need to specify the sourcepath. For example, if you were to run javadocs in in C:\, you would modify the command as such:

C:\> javadoc -d [path to javadoc destination directory] -sourcepath [path to package directory] [package name]

C:\> javadoc -d C:\javadoc\test -sourcepath C:\projects com.test

If you want to run javadocs on only selected .java files, then add the source filenames separated by spaces (you can use an asterisk (*) for a wildcard). Make sure to include the path to the files:

C:\> javadoc -d [path to javadoc destination directory] [source filenames]

C:\> javadoc -d C:\javadoc\test C:\projects\com\test\file1.java

More information/scenarios can be found here.

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

http://api.jquery.com/jQuery.post/

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

Why do I have to "git push --set-upstream origin <branch>"?

My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.

Push and set upstream (remote) repository as origin:

$ git push -u origin

Next time you push, you don't have to specify the remote repository:

$ git push

How to convert an image to base64 encoding?

You can also do this via curl, just you need a path to an image file and pass it to the function given below..

public static function getImageDataFromUrl($url)
{
    $urlParts = pathinfo($url);
    $extension = $urlParts['extension'];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
    return $base64;

}

Intro to GPU programming

CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

How to import existing Git repository into another?

Let me use names a (in place of XXX and ZZZ) and b (in place of YYY), since that makes the description a bit easier to read.

Say you want to merge repository a into b (I'm assuming they're located alongside one another):

cd a
git filter-repo --to-subdirectory-filter a
cd ..
cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a

For this you need git-filter-repo installed (filter-branch is discouraged).

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

More on it here.

Disable elastic scrolling in Safari

You could check if the scroll-offsets are in the bounds. If they go beyond, set them back.

var scrollX = 0;
var scrollY = 0;
var scrollMinX = 0;
var scrollMinY = 0;
var scrollMaxX = document.body.scrollWidth - window.innerWidth;
var scrollMaxY = document.body.scrollHeight - window.innerHeight;

// make sure that we work with the correct dimensions
window.addEventListener('resize', function () {
  scrollMaxX = document.body.scrollWidth - window.innerWidth;
  scrollMaxY = document.body.scrollHeight - window.innerHeight;
}, false);

// where the magic happens
window.addEventListener('scroll', function () {
  scrollX = window.scrollX;
  scrollY = window.scrollY;

  if (scrollX <= scrollMinX) scrollTo(scrollMinX, window.scrollY);
  if (scrollX >= scrollMaxX) scrollTo(scrollMaxX, window.scrollY);

  if (scrollY <= scrollMinY) scrollTo(window.scrollX, scrollMinY);
  if (scrollY >= scrollMaxY) scrollTo(window.scrollX, scrollMaxY);
}, false);

http://jsfiddle.net/yckart/3YnUM/

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

This is related to compact option of Babel compiler, which commands to "not include superfluous whitespace characters and line terminators. When set to 'auto' compact is set to true on input sizes of >100KB." By default its value is "auto", so that is probably the reason you are getting the warning message. See Babel documentation.

You can change this option from Webpack using a query parameter. For example:

loaders: [
    { test: /\.js$/, loader: 'babel', query: {compact: false} }
]

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

Find unique lines

sort -d "file name" | uniq -u

this worked for me for a similar one. Use this if it is not arranged. You can remove sort if it is arranged

How to add title to subplots in Matplotlib?

If you want to make it shorter, you could write :

import matplolib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()

It makes it maybe less clear but you don't need more lines or variables

Javascript to open popup window and disable parent window

Hi the answer that @anu posted is right, but it wont completely work as required. By making a slight change to child_open() function it works properly.

<html>
<head>
<script type="text/javascript">

var popupWindow=null;

function child_open()
{ 
if(popupWindow && !popupWindow.closed)
   popupWindow.focus();
else
   popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");

}
function parent_disable() {
  if(popupWindow && !popupWindow.closed)
    popupWindow.focus();
}
</script>
</head>
  <body onFocus="parent_disable();" onclick="parent_disable();">
     <a href="javascript:child_open()">Click me</a>
  </body>    
</html>

How to animate CSS Translate

I too was looking for a good way to do this, I found the best way was to set a transition on the "transform" property and then change the transform and then remove the transition.

I put it all together in a jQuery plugin

https://gist.github.com/dustinpoissant/8a4837c476e3939a5b3d1a2585e8d1b0

You would use the code like this:

$("#myElement").animateTransform("rotate(180deg)", 750, function(){
  console.log("animation completed after 750ms");
});

How can I generate Unix timestamps?

In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME

How to get named excel sheets while exporting from SSRS

The Rectangle method

The simplest and most reliable way I've found of achieving worksheets/page-breaks is with use of the rectangle tool.

Group your page within rectangles or a single rectangle that fills the page in a sub-report, as follows:

  • The quickest way I've found of placing the rectangle is to draw it around the objects you wish to place in the rectangle.

  • Right click and in the layout menu, send the rectangle to back.

  • Select all your objects and drag them slightly, but be sure they land in the same place they were. They will all now be in the rectangle.

In the rectangle properties you can set the page-break to occur at the start or end of the rectangle and name of the page can be based on an expression.

The worksheets will be named the same as the name of the page.

Duplicate names will have a number in brackets suffix.

Note: Ensure that the names are valid worksheet names.

Android button font size

I tried to put the font size in the styles.xml but when i went to use it it was only allowing resources from the dimen folder so put it in there instead, dont know it this is right

        <Button
                android:layout_weight="1"
                android:id="@+id/three_btn"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:onClick="onButtonClick"
                android:textColor="#EEEEEE"
                android:textStyle="bold"
                android:textSize="@dimen/buttonFontSize"
                android:text="3"/>

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Executing multi-line statements in the one-line command-line?

this style can be used in makefiles too (and in fact it is used quite often).

python - <<EOF
import sys
for r in range(3): print 'rob'
EOF

or

python - <<-EOF
    import sys
    for r in range(3): print 'rob'
EOF

in latter case leading tab characters are removed too (and some structured outlook can be achieved)

instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).

How to call getClass() from a static method in Java?

I had the same problem ! but to solve it just modify your code as following.

public static void startMusic() {
URL songPath = YouClassName.class.getClassLoader().getResource("background.midi");
}

this worked fine with me hope it will also work fine with you.

Import existing source code to GitHub

Actually, if you opt for creating an empty repo on GitHub it gives you exact instructions that you can almost copy and paste into your terminal which are (at this point in time):

…or create a new repository on the command line

echo "# ..." >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin [email protected]:<user>/<repo>.git
git push -u origin master

How to write and read a file with a HashMap?

HashMap implements Serializable so you can use normal serialization to write hashmap to file

Here is the link for Java - Serialization example

How to make a page redirect using JavaScript?

You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:

<a href="your_page.php?var1=value1&var2=value2">

You separate each of those values with the & sign.

Or you can create this on a button click like this:

<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">

Represent space and tab in XML tag

Work for me

\n = &#xA;
\r = &#xD;
\t = &#x9;
space = &#x20;

Here is an example on how to use them in XML

<KeyWord name="hello&#x9;" />

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"