Programs & Examples On #Rack

Rack provides a minimal interface between webservers supporting Ruby and Ruby frameworks.

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

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

From the docs:

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

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

Edit: Further reading led me here:

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

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

A failure occurred while executing com.android.build.gradle.internal.tasks

In my case problem arose due to gradle version upgradation from 6.2 all to 6.6 all in gradle wrapper. So i wiped out data of avd and restarted it and then deleted .gradle folder in android/.gradle and then run yarn start --reset-cache and yarn android. Then it worked for me

error: This is probably not a problem with npm. There is likely additional logging output above

I already have the same problem . and I fix it using npm update & npm cache clean --force

Why do I keep getting Delete 'cr' [prettier/prettier]?

Add this to your .prettierrc file and open the VSCODE

"endOfLine": "auto"

How to compare oldValues and newValues on React Hooks useEffect?

I just published react-delta which solves this exact sort of scenario. In my opinion, useEffect has too many responsibilities.

Responsibilities

  1. It compares all values in its dependency array using Object.is
  2. It runs effect/cleanup callbacks based on the result of #1

Breaking Up Responsibilities

react-delta breaks useEffect's responsibilities into several smaller hooks.

Responsibility #1

Responsibility #2

In my experience, this approach is more flexible, clean, and concise than useEffect/useRef solutions.

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

In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.

"babel": {
"presets": [
  "@babel/preset-env",
  "@babel/preset-react"
],
"plugins": [
  "@babel/plugin-proposal-class-properties"
]}

Note: Don't forget to exit the console and reopen before executing the npm or yarn commands.

git clone: Authentication failed for <URL>

Rather than escape my password I left it out and was prompted for it, but only when I included the domain name before my username:

git clone https://some-dom-name\[email protected]/tfs/...

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

I had the same error and I solved it by importing HttpModule in app.module.ts

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

and then in the imports[] array:

HttpModule

Default interface methods are only supported starting with Android N

My project use ButterKnife and Retro lambda, setting JavaVersion.VERSION_1_8 will not work. It always blames at ButterKnife static interface function until I found this Migrate from Retrolambda

TL;DR

Just add JavaVersion.VERSION_1_8 and completely REMOVE retrolambda from your project. It will build successfully.

How can I change the app display name build with Flutter?

There are several possibilities:

1- The use of a package:

I suggest you to use flutter_launcher_name because of the command-line tool which simplifies the task of updating your Flutter app's launcher name.

Usage:

Add your Flutter Launcher name configuration to your pubspec.yaml file:

dev_dependencies:
  flutter_launcher_name: "^0.0.1"

flutter_launcher_name:
  name: "yourNewAppLauncherName"

After setting up the configuration, all that is left to do is run the package.

flutter pub get
flutter pub run flutter_launcher_name:main

If you use this package, you don't need modify file AndroidManifest.xml or Info.plist.

2- Edit AndroidManifest.xml for Android and info.plist for iOS

For Android, edit only android:label value in the application tag in file AndroidManifest.xml located in the folder: android/app/src/main

Code:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Your Application Name"  //here
        android:icon="@mipmap/ic_launcher">
        <activity>
        <!--  -->
        </activity>
    </application>
</manifest>

Screenshot:

Enter image description here

For iOS, edit only the value inside the String tag in file Info.plist located in the folder ios/Runner .

Code:

<plist version="1.0">
<dict>
    <key>CFBundleName</key>
    <string>Your Application Name </string>  //here
</dict>
</plist>

Screenshot:

Enter image description here

Do a flutter clean and restart your application if you have a problem.

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

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

yo need create the user "pma" in mysql or change this lines(user and password for mysql):

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma'; 
$cfg['Servers'][$i]['controlpass'] = '';

Linux: /etc/phpmyadmin/config.inc.php

get list of packages installed in Anaconda

For script creation at Windows cmd or powershell prompt:

C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
conda list
pip list

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

You may had set different passwords for user 'root' or have been changed your password. I had same error as :

mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES)

and I found that my root password for phpmyAdmin is not same on both 'mysql' and 'phpmyadmin' databases, so I updated my password for 'phpmyadmin' database same as 'mysql' database as follow:

sudo gedit /etc/phpmyadmin/config-db.php

and update the fields

$dbuser='root';

$dbpass='myNewPassword'; <-- update your new password here

Best wishes!

Python TypeError must be str not int

Python comes with numerous ways of formatting strings:

New style .format(), which supports a rich formatting mini-language:

>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!

Old style % format specifier:

>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!

In Py 3.6 using the new f"" format strings:

>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!

Or using print()s default separator:

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

And least effectively, construct a new string by casting it to a str() and concatenating:

>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!

Or join()ing it:

>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!

Error: the entity type requires a primary key

This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.

Although you've attempted to do so:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits record from the database, it constructs a Fruit object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.

You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter.

SQL Query Where Date = Today Minus 7 Days

Use the following:

WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())

Hope this helps.

How can I create an observable with a delay

import * as Rx from 'rxjs/Rx';

We should add the above import to make the blow code to work

Let obs = Rx.Observable
    .interval(1000).take(3);

obs.subscribe(value => console.log('Subscriber: ' + value));

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

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

No value accessor for form control

enter image description here

enter image description here

You can see formControlName in label , removing this solved my problem

Maximum call stack size exceeded on npm install

rm -rf node_modules

and then reinstall worked for me.

note: probably don't need to rip out your lock files

OpenCV NoneType object has no attribute shape

This is because the path of image is wrong or the name of image you write is incorrect .

how to check? first try to print the image using print(img) if it prints 'None' that means you have given wrong image path correct that path and try again.

Angular2: Cannot read property 'name' of undefined

In Angular, there is the support elvis operator ?. to protect against a view render failure. They call it the safe navigation operator. Take the example below:

The current person name is {{nullObject?.name}}

Since it is trying to access name property of a null value, the whole view disappears and you can see the error inside the browser console. It works perfectly with long property paths such as a?.b?.c?.d. So I recommend you to use it everytime you need to access a property inside a template.

Updates were rejected because the tip of your current branch is behind its remote counterpart

Set current branch name like master

git pull --rebase origin master git push origin master

Or branch name develop

git pull --rebase origin develop git push origin develop

@viewChild not working - cannot read property nativeElement of undefined

@ViewChild('keywords-input') keywordsInput; doesn't match id="keywords-input"

id="keywords-input"

should be instead a template variable:

#keywordsInput

Note that camel case should be used, since - is not allowed in template reference names.

@ViewChild() supports names of template variables as string:

@ViewChild('keywordsInput') keywordsInput;

or component or directive types:

@ViewChild(MyKeywordsInputComponent) keywordsInput;

See also https://stackoverflow.com/a/35209681/217408

Hint:
keywordsInput is not set before ngAfterViewInit() is called

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

Go to

File->settings->Buil,Execution,Deployment->Instant Run->Disable it.

//now you are good to go.

ASP.NET Core Identity - get current user

Assuming your code is inside an MVC controller:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

From the Controller base class, you can get the IClaimsPrincipal from the User property

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

You can check the claims directly (without a round trip to the database):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

Other fields can be fetched from the database's User entity:

  1. Get the user manager using dependency injection

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. And use it:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

Getting "Cannot call a class as a function" in my React Project

Mostly these issues occur when you miss extending Component from react:

import React, {Component} from 'react'

export default class TimePicker extends Component {
    render() {
        return();     
    }
}

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

In my case was facing the same issue, especially the first pull request trying after remotely adding a Git repository. The following error was facing.

fatal: refusing to merge unrelated histories on every try

Use the --allow-unrelated-histories command. It works perfectly.

git pull origin branchname --allow-unrelated-histories

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try these some steps:

Stop Mysql Service 1st sudo /etc/init.d/mysql stop

Login as root without password sudo mysqld_safe --skip-grant-tables &

After login mysql terminal you should need execute commands more:

use mysql;

UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';

flush privileges;

sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown

After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04

Why do I have to "git push --set-upstream origin <branch>"?

If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

Printing an int list in a single line python3

these will both work in Python 2.7 and Python 3.x:

>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3

btw, array is a reserved word in Python.

git status (nothing to commit, working directory clean), however with changes commited

git status output tells you three things by default:

  1. which branch you are on
  2. What is the status of your local branch in relation to the remote branch
  3. If you have any uncommitted files

When you did git commit , it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.

If you find the output of git status verbose and difficult to comprehend, try using git status -sb this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:

master...origin/master [ahead 1]

git status is pretty useful, in the workflow you described do a git status -sb: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.

Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.

CSS3 100vh not constant in mobile browser

The following code solved the problem (with jQuery).

var vhHeight = $("body").height();
var chromeNavbarHeight = vhHeight - window.innerHeight;
$('body').css({ height: window.innerHeight, marginTop: chromeNavbarHeight });

And the other elements use % as a unit to replace vh.

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked

I had the same issue (EF Core) while setting up xUnit tests. What 'fixed' it for me in testing was looping through the change tracker entities after setting up the seed data.

  • at the bottom of the SeedAppDbContext() method.

I set up a Test Mock Context:

/// <summary>
/// Get an In memory version of the app db context with some seeded data
/// </summary>
public static AppDbContext GetAppDbContext(string dbName)
{
    //set up the options to use for this dbcontext
    var options = new DbContextOptionsBuilder<AppDbContext>()
        .UseInMemoryDatabase(databaseName: dbName)
        //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
        .Options;

    var dbContext = new AppDbContext(options);
    dbContext.SeedAppDbContext();
    return dbContext;
}

Extension method to add some seed data:

  • and detach entities in foreach loop at bottom of method.
    public static void SeedAppDbContext(this AppDbContext appDbContext)
    {
       // add companies
       var c1 = new Company() { Id = 1, CompanyName = "Fake Company One", ContactPersonName = "Contact one", eMail = "[email protected]", Phone = "0123456789", AdminUserId = "" };
       c1.Address = new Address() { Id = 1, AddressL1 = "Field Farm", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(c1);
                        
       var nc1 = new Company() { Id = 2, CompanyName = "Test Company 2", ContactPersonName = "Contact two", eMail = "[email protected]", Phone = "0123456789", Address = new Address() { }, AdminUserId = "" };
       nc1.Address = new Address() { Id = 2, AddressL1 = "The Barn", AddressL2 = "Some Lane", City = "some city", PostalCode = "AB12 3CD" };
       appDbContext.CompanyRecords.Add(nc1);

       //....and so on....
            
       //last call to commit everything to the memory db
       appDbContext.SaveChanges();

       //and then to detach everything 
       foreach (var entity in appDbContext.ChangeTracker.Entries())
       {
           entity.State = EntityState.Detached;
       }
    }

The controller put method

The .ConvertTo<>() Method is an extension method from ServiceStack

 [HttpPut]
public async Task<IActionResult> PutUpdateCompany(CompanyFullDto company)
{
    if (0 == company.Id)
        return BadRequest();
    try
    {
        Company editEntity = company.ConvertTo<Company>();
        
        //Prior to detaching an error thrown on line below (another instance with id)
        var trackedEntity = _appDbContext.CompanyRecords.Update(editEntity);
        

        await _appDbContext.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException dbError)
    {
        if (!CompanyExists(company.Id))
            return NotFound();
        else
            return BadRequest(dbError);
    }
    catch (Exception Error)
    {
        return BadRequest(Error);
    }
    return Ok();
}

and the test:

    [Fact]
    public async Task PassWhenEditingCompany()
    {
        var _appDbContext = AppDbContextMocker.GetAppDbContext(nameof(CompaniesController));
        var _controller = new CompaniesController(null, _appDbContext);

        //Arrange
        const string companyName = "Fake Company One";
        const string contactPerson = "Contact one";

        const string newCompanyName = "New Fake Company One";
        const string newContactPersonName = "New Contact Person";

        //Act
        var getResult = _controller.GetCompanyById(1);
        var getEntity = (getResult.Result.Result as OkObjectResult).Value;
        var entityDto = getEntity as CompanyFullDto;


        //Assert
        Assert.Equal(companyName, entityDto.CompanyName);
        Assert.Equal(contactPerson, entityDto.ContactPersonName);
        Assert.Equal(1, entityDto.Id);

        //Arrange
        Company entity = entityDto.ConvertTo<Company>();
        entity.CompanyName = newCompanyName;
        entity.ContactPersonName = newContactPersonName;
        CompanyFullDto entityDtoUpd = entity.ConvertTo<CompanyFullDto>();

        //Act
        var result = await _controller.PutUpdateCompany(entityDtoUpd) as StatusCodeResult;

        //Assert           
        Assert.True(result.StatusCode == 200);

        //Act
        getResult = _controller.GetCompanyById(1);
        getEntity = (getResult.Result.Result as OkObjectResult).Value;
        
        entityDto = getEntity as CompanyFullDto;
        
        //Assert
        Assert.Equal(1, entityDto.Id); // didn't add a new record
        Assert.Equal(newCompanyName, entityDto.CompanyName); //updated the name
        Assert.Equal(newContactPersonName, entityDto.ContactPersonName); //updated the contact

//make sure to dispose of the _appDbContext otherwise running the full test will fail.
_appDbContext.Dispose();
    }

When should I use curly braces for ES6 import?

Dan Abramov's answer explains about the default exports and named exports.

Which to use?

Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

However, in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references. Named exports is also preferred for utilities.

Overall use whatever you prefer.

Additional

Default export is actually a named export with name default, so default export can be imported as:

import {default as Sample} from '../Sample.js';

Git pull - Please move or remove them before you can merge

Apparently the files were added in remote repository, no matter what was the content of .gitignore file in the origin.

As the files exist in the remote repository, git has to pull them to your local work tree as well and therefore complains that the files already exist.

.gitignore is used only for scanning for the newly added files, it doesn't have anything to do with the files which were already added.

So the solution is to remove the files in your work tree and pull the latest version. Or the long-term solution is to remove the files from the repository if they were added by mistake.

A simple example to remove files from the remote branch is to

$git checkout <brachWithFiles>
$git rm -r *.extension
$git commit -m "fixin...."
$git push

Then you can try the $git merge again

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Well, I believe the question is answered and has already been accepted. But I am going to write what I faced and how I solved it.

I did receive also the same error:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1

I wasn't fortunate to apply all the settings and got success. But when I tried to Debug the project again. This time I got Three Error (including above):

Error:Java HotSpot(TM) 64-Bit Server VM warning: CodeCache is full. Compiler has been disabled.

and

Error:Java HotSpot(TM) 64-Bit Server VM warning: Try increasing the code cache size using -XX:ReservedCodeCacheSize=

So what I did? I just go to Android Studio:

File > Invalidate Caches / Restart.. > Invalidate & Restart

Quick Fix!

Extra Note:

What I found in Gradle Console:

:app:incrementalDebugTasks :app:prePackageMarkerForDebug :app:fastDeployDebugExtractor :app:generateDebugInstantRunAppInfo :app:transformClassesWithDexForDebug To run dex in process, the Gradle daemon needs a larger heap. It currently has approximately 910 MB. For faster builds, increase the maximum heap size for the Gradle daemon to more than 2048 MB. To do this set org.gradle.jvmargs=-Xmx2048M in the project gradle.properties. For more information see https://docs.gradle.org/current/userguide/build_environment.html :app:transformClassesWithDexForDebug FAILED

Read More about it Here on Oracle Blog

github: server certificate verification failed

It can be also self-signed certificate, etc. Turning off SSL verification globally is unsafe. You can install the certificate so it will be visible for the system, but the certificate should be perfectly correct.

Or you can clone with one time configuration parameter, so the command will be:

git clone -c http.sslverify=false https://myserver/<user>/<project>.git;

GIT will remember the false value, you can check it in the <project>/.git/config file.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this issue after converting my Write-Host cmdlets to Write-Information and I was missing quotes and parens around the parameters. The cmdlet signatures are evidently not the same.

Write-Host this is a good idea $here
Write-Information this is a good idea $here <=BAD

This is the cmdlet signature that corrected after spending 20-30 minutes digging down the function stack...

Write-Information ("this is a good idea $here") <=GOOD

ngFor with index as value in attribute

I would use this syntax to set the index value into an attribute of the HTML element:

Angular >= 2

You have to use let to declare the value rather than #.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Angular = 1

<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

How to get current route in react-router 2.0.0-rc5

After reading some more document, I found the solution:

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

I just need to access the injected property location of the instance of the component like:

var currentLocation = this.props.location.pathname

configuring project ':app' failed to find Build Tools revision

In my case issue was with wrong path to NDK.

If your project requires it please check it in menu File -> Project Structure -> SDK Location:

enter image description here

Brackets.io: Is there a way to auto indent / format <html>

You can install an indentator package.

Click on File > Extension Manager....

Look for the search field and type: Indentator > Install

Once Indentator is installed, you can use Ctrl + Alt + I

Ubuntu, how do you remove all Python 3 but not 2

neither try any above ways nor sudo apt autoremove python3 because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome on kernal.

try to change your default python version instead removing it. you can do this through bashrc file or export path command.

Make view 80% width of parent in React Native

The easiest way to achieve is by applying width to view.

width: '80%'

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

This is due to sometimes the session query may have invalid characters, try clicking on the highlighted icons in PHPMYADMIN, and it will be resolved, because session values resetted to defaults See Image

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

No module named serial

it may be very old post, but I would like to share my experience. I had the same issue when I used Pycharm and I installed the package from Project Interpreter page in the Project Settings/Preferences... That fixed the issue, please check below link: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html?_ga=2.41088674.1813230270.1594526819-1842497340.1594080707

UITableView example for Swift

The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:

enter image description here

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"
    
    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        
        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }
    
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        
        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]
        
        return cell
    }
    
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

Read the in-code comments to see what is happening. The highlights are

  • The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

Drag a UITableView onto your View Controller. Use auto layout to pin the four sides.

enter image description here

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.

Finished

That's all. You should be able run your app now.

This answer was tested with Xcode 9 and Swift 4


Variations

Row Deletion

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.

enter image description here

Row Spacing

If you would like to have spacing between your rows, see this supplemental example.

enter image description here

Custom cells

The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.

enter image description here

Dynamic Cell Height

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.

enter image description here

Further Reading

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Error: Execution failed for task ':app:clean'. Unable to delete file

I had the same problem and I solved it by moving project folder into ext4 partition

NodeJS accessing file with relative path

Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments

Parse JSON String into List<string>

Wanted to post this as a comment as a side note to the accepted answer, but that got a bit unclear. So purely as a side note:

If you have no need for the objects themselves and you want to have your project clear of further unused classes, you can parse with something like:

var list = JObject.Parse(json)["People"].Select(el => new { FirstName = (string)el["FirstName"], LastName = (string)el["LastName"] }).ToList();

var firstNames = list.Select(p => p.FirstName).ToList();
var lastNames = list.Select(p => p.LastName).ToList();

Even when using a strongly typed person class, you can still skip the root object by creating a list with JObject.Parse(json)["People"].ToObject<List<Person>>() Of course, if you do need to reuse the objects, it's better to create them from the start. Just wanted to point out the alternative ;)

Slack URL to open a channel from browser

Sure you can:

https://<organization>.slack.com/messages/<channel>/

for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)

There is no tracking information for the current branch

git branch --set-upstream-to=origin/main

Extract column values of Dataframe as List in Apache Spark

In Scala and Spark 2+, try this (assuming your column name is "s"): df.select('s).as[String].collect

Node JS Promise.all and forEach

Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.

/**
 * 
 * @param items An array of items.
 * @param fn A function that accepts an item from the array and returns a promise.
 * @returns {Promise}
 */
function forEachPromise(items, fn) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item);
        });
    }, Promise.resolve());
}

And use it like this:

var items = ['a', 'b', 'c'];

function logItem(item) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            resolve();
        })
    });
}

forEachPromise(items, logItem).then(() => {
    console.log('done');
});

We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.

function forEachPromise(items, fn, context) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item, context);
        });
    }, Promise.resolve());
}

Your promise function would look like this:

function logItem(item, context) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            context.itemCount++;
            resolve();
        })
    });
}

data.map is not a function

data is not an array, it is an object with an array of products so iterate over data.products

var allProducts = data.products.map(function (item) {
    return new getData(item);
});

Getting absolute URLs using ASP.NET Core

If you just want to convert a relative path with optional parameters I created an extension method for IHttpContextAccessor

public static string AbsoluteUrl(this IHttpContextAccessor httpContextAccessor, string relativeUrl, object parameters = null)
{
    var request = httpContextAccessor.HttpContext.Request;

    var url = new Uri(new Uri($"{request.Scheme}://{request.Host.Value}"), relativeUrl).ToString();

    if (parameters != null)
    {
        url = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(url, ToDictionary(parameters));
    }

    return url;
}


private static Dictionary<string, string> ToDictionary(object obj)
{
    var json = JsonConvert.SerializeObject(obj);
    return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}

You can then call the method from your service/view using the injected IHttpContextAccessor

var callbackUrl = _httpContextAccessor.AbsoluteUrl("/Identity/Account/ConfirmEmail", new { userId = applicationUser.Id, code });

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

In my case my problem was that I was using an older version of NetBeans. The Maven repository removed an http reference, but the embedded Maven in Netbeans had that http reference hard-coded. I was really confused at first because my pom.xml referenced the proper https://repo.maven.apache.org/maven2.

Fixing it was pretty simple. I downloaded the latest zip archive of Maven from the following location and extracted it to my machine: https://maven.apache.org/download.cgi

Within Netbeans at Tools -> Options -> Java -> Maven on the "Execution" section I set "Maven Home" to the newly extracted zip file location.

Now I could build my project....

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

If you are using intellij and want to use gradle you need to add this to the dependencies section of build.gradle file:

testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")

React-Router open Link in new tab

In React Router version 5.0.1 and above, you can use:

<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I got stuck on this error because in the class that has the @SpringBootApplication I forgot to specify the controller's package name.

I wanted to be more specific this time pointing out which components Spring had to scan, instead of configuring the base package.

It was like this:

@ComponentScan(basePackages = {"br.com.company.project.repository", "br.com.company.project.service"})

But the correct form is one of these:

@ComponentScan(basePackages = {"br.com.company.project.repository", "br.com.company.project.service", "br.com.company.project.controller"})

@ComponentScan(basePackages = {"br.com.company.project")

I decided to share my solution, because although the correct answer is very comprehensive, it doesn't cover this (idiotic) mistake :)

How do I jump to a closing bracket in Visual Studio Code?

enter image description here

(For anybody looking how to do it in Visual Studio!)

Change the Arrow buttons in Slick slider

Content property of pseudo element :before accepts images too. In slick-theme.css change:

_x000D_
_x000D_
// change_x000D_
$slick-prev-character: "?" !default; _x000D_
_x000D_
// to_x000D_
$slick-prev-character: url('image-prev.png');_x000D_
_x000D_
// and _x000D_
$slick-next-character: "?" !default;_x000D_
_x000D_
// to _x000D_
$slick-next-character: url('image-next.jpg');
_x000D_
_x000D_
_x000D_

or directly change the content property on slick-prev:before and slick-next:before

_x000D_
_x000D_
.slick-prev {_x000D_
    left: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: auto;_x000D_
        right: -25px;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-next.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
.slick-next {_x000D_
    right: -25px;_x000D_
    [dir="rtl"] & {_x000D_
        left: -25px;_x000D_
        right: auto;_x000D_
    }_x000D_
    &:before {_x000D_
        content: url('image-next.jpg'); // <<<<<<<<_x000D_
        [dir="rtl"] & {_x000D_
            content: url('image-prev.jpg'); // <<<<<<<<_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to resolve TypeError: Cannot convert undefined or null to object

Make sure that destination object is not empty ( null or undefined ).

You can initialize destination object with empty object like below:

var destinationObj = {};

Object.assign(destinationObj, sourceObj);

I just assigned a variable, but echo $variable shows something else

You may want to know why this is happening. Together with the great explanation by that other guy, find a reference of Why does my shell script choke on whitespace or other special characters? written by Gilles in Unix & Linux:

Why do I need to write "$foo"? What happens without the quotes?

$foo does not mean “take the value of the variable foo”. It means something much more complex:

  • First, take the value of the variable.
  • Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains foo * bar ? then the result of this step is the 3-element list foo, *, bar.
  • Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing foo, following by the list of files in the current directory, and finally bar. If the current directory is empty, the result is foo, *, bar.

Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception: "$@" to expand to the list of positional parameters, e.g. "$@" is equivalent to "$1" "$2" "$3" if there are three positional parameters. See What is the difference between $* and $@?)

The same happens to command substitution with $(foo) or with `foo`. On a side note, don't use `foo`: its quoting rules are weird and non-portable, and all modern shells support $(foo) which is absolutely equivalent except for having intuitive quoting rules.

The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming IFS doesn't contain digits or -).

See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.

Unless you mean for all this rigmarole to happen, just remember to always use double quotes around variable and command substitutions. Do take care: leaving out the quotes can lead not just to errors but to security holes.

How to send post request to the below post method using postman rest client

JSON:-

For POST request using json object it can be configured by selecting

Body -> raw -> application/json

POST JSON object using POSTMAN

Form Data(For Normal content POST):- multipart/form-data

For normal POST request (using multipart/form-data) it can be configured by selecting

Body -> form-data

POST multipart/form-data using POSTMAN

Hadoop cluster setup - java.net.ConnectException: Connection refused

I had the similar prolem with OP. As the terminal output suggested, I went to http://wiki.apache.org/hadoop/ConnectionRefused

I tried to change my /etc/hosts file as suggested here, i.e. remove 127.0.1.1 as OP suggested it will create another error.

So in the end, I leave it as is. The following is my /etc/hosts

127.0.0.1       localhost.localdomain   localhost
127.0.1.1       linux
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

In the end, I found that my namenode did not started correctly, i.e. When you type sudo netstat -lpten | grep java in the terminal, there will not be any JVM process running(listening) on port 9000.

So I made two directories for namenode and datanode respectively(if you have not done so). You don't have to put where I put it, please replace it based on your hadoop directory. i.e.

mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/namenode
mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/datanode

I reconfigured my hdfs-site.xml.

<configuration>
    <property>
        <name>dfs.replication</name>
        <value>1</value>
    </property>
   <property>
        <name>dfs.namenode.name.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/namenode</value>
    </property>
    <property>
        <name>dfs.datanode.data.dir</name>
        <value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/datanode</value>
    </property>
</configuration>

In terminal, stop your hdfs and yarn with script stop-dfs.sh and stop-yarn.sh. They are located in your hadoop directory/sbin. In my case, it's /home/hadoopuser/hadoop-2.6.2/sbin/.

Then start your hdfs and yarn with script start-dfs.sh and start-yarn.sh After it is started, type jps in your terminal to see if your JVM processes are running correctly. It should show the following.

15678 NodeManager
14982 NameNode
15347 SecondaryNameNode
23814 Jps
15119 DataNode
15548 ResourceManager

Then try to use netstat again to see if your namenode is listening to port 9000

sudo netstat -lpten | grep java

If you successfully set up the namenode, you should see the following in your terminal output.

tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 1001 175157 14982/java

Then try to type the command hdfs dfs -mkdir /user/hadoopuser If this command executes sucessfully, now you can list your directory in the HDFS user directory by hdfs dfs -ls /user

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

Why docker container exits immediately

Since the image is a linux, one thing to check is to make sure any shell scripts used in the container have unix line endings. If they have a ^M at the end then they are windows line endings. One way to fix them is with dos2unix on /usr/local/start-all.sh to convert them from windows to unix. Running the docker in interactive mode can help figure out other problems. You could have a file name typo or something. see https://en.wikipedia.org/wiki/Newline

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I have the same problem, fix the ret in capture video

import numpy as np
import cv2

# Capture video from file
cap = cv2.VideoCapture('video1.avi')

while True:

    ret, frame = cap.read()

    if ret == True:

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cv2.imshow('frame',gray)


        if cv2.waitKey(30) & 0xFF == ord('q'):
            break

    else:
        break

cap.release()
cv2.destroyAllWindows()

How to configure Docker port mapping to use Nginx as an upstream proxy?

Just found an article from Anand Mani Sankar wich shows a simple way of using nginx upstream proxy with docker composer.

Basically one must configure the instance linking and ports at the docker-compose file and update upstream at nginx.conf accordingly.

Why does git status show branch is up-to-date when changes exist upstream?

This is because your local repo hasn't checked in with the upstream remotes. To have this work as you're expecting it to, use git fetch then run a git status again.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

Here too I can reproduce this problem with scrapy and psycopg2 (both require C++ compiling), even though I have Microsoft Visual C++ Compiler for Python 2.7 installed.

It has to be noted that I use virtualenv. From your post I'm not sure whether you do the same.

Anyway I tried to skip the activation of the virtual environment. Then both scrapy and psycopg2 installed fine.

My hypothesis: there is a conflict between this 2014 C++ compiler for Python and virtualenv. I do not know why nor how to solve it (and I'd be glad if someone can suggest a workaround).

How do I make WRAP_CONTENT work on a RecyclerView

This now works as they've made a release in version 23.2, as stated in this post. Quoting the official blogpost

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

How to add/update child entities when updating a parent entity in EF

OK guys. I had this answer once but lost it along the way. absolute torture when you know there's a better way but can't remember it or find it! It's very simple. I just tested it multiple ways.

var parent = _dbContext.Parents
  .Where(p => p.Id == model.Id)
  .Include(p => p.Children)
  .FirstOrDefault();

parent.Children = _dbContext.Children.Where(c => <Query for New List Here>);
_dbContext.Entry(parent).State = EntityState.Modified;

_dbContext.SaveChanges();

You can replace the whole list with a new one! The SQL code will remove and add entities as needed. No need to concern yourself with that. Be sure to include child collection or no dice. Good luck!

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

Try this:

android {
configurations {
        all*.exclude  module: 'PhotoView'  //???????
    }
}

Best way to add Gradle support to IntelliJ Project

  1. Add build.gradle in your project's root directory.

  2. Then just File -> Invalidate Caches / Restart

Here is a basic build.gradle for Java projects:

plugins {
    id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'

Python IndentationError unindent does not match any outer indentation level

You are mixing tabs and spaces. Don't do that. Specifically, the __init__ function body is indented with tabs while your on_data method is not.

Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:

highlighted code with tabs shown as lines

You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.

Run your code with:

python -tt scriptname.py

and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.

How do I remove my IntelliJ license in 2019.3?

For Linux to reset current 30 days expiration license, you must run code:

rm ~/.config/JetBrains/IntelliJIdea2019.3/options/other.xml
rm -rf ~/.config/JetBrains/IntelliJIdea2019.3/eval/*
rm -rf .java/.userPrefs

How to detect query which holds the lock in Postgres?

Postgres has a very rich system catalog exposed via SQL tables. PG's statistics collector is a subsystem that supports collection and reporting of information about server activity.

Now to figure out the blocking PIDs you can simply query pg_stat_activity.

select pg_blocking_pids(pid) as blocked_by
from pg_stat_activity
where cardinality(pg_blocking_pids(pid)) > 0;

To, get the query corresponding to the blocking PID, you can self-join or use it as a where clause in a subquery.

SELECT query
FROM pg_stat_activity
WHERE pid IN (select unnest(pg_blocking_pids(pid)) as blocked_by from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0);

Note: Since pg_blocking_pids(pid) returns an Integer[], so you need to unnest it before you use it in a WHERE pid IN clause.

Hunting for slow queries can be tedious sometimes, so have patience. Happy hunting.

Material Design not styling alert dialogs

UPDATED ON Aug 2019 WITH The Material components for android library:

With the new Material components for Android library you can use the new com.google.android.material.dialog.MaterialAlertDialogBuilder class, which extends from the existing androidx.appcompat.AlertDialog.Builder class and provides support for the latest Material Design specifications.

Just use something like this:

new MaterialAlertDialogBuilder(context)
            .setTitle("Dialog")
            .setMessage("Lorem ipsum dolor ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

You can customize the colors extending the ThemeOverlay.MaterialComponents.MaterialAlertDialog style:

  <style name="CustomMaterialDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
     <!-- Background Color-->
     <item name="android:background">#006db3</item>
     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/secondaryColor</item>
     <!-- Text Color for buttons -->
     <item name="colorPrimary">@color/white</item> 
     ....
  </style>  

To apply your custom style just use the constructor:

new MaterialAlertDialogBuilder(context, R.style.CustomMaterialDialog)

enter image description here

To customize the buttons, the title and the body text check this post for more details.

You can also change globally the style in your app theme:

 <!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="materialAlertDialogTheme">@style/CustomMaterialDialog</item>
 </style>

WITH SUPPORT LIBRARY and APPCOMPAT THEME:

With the new AppCompat v22.1 you can use the new android.support.v7.app.AlertDialog.

Just use a code like this:

import android.support.v7.app.AlertDialog

AlertDialog.Builder builder =
       new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Dialog");
builder.setMessage("Lorem ipsum dolor ....");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

And use a style like this:

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">#FFCC00</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:background">#5fa3d0</item>
    </style>

Otherwise you can define in your current theme:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- your style -->
    <item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>

and then in your code:

 import android.support.v7.app.AlertDialog

    AlertDialog.Builder builder =
           new AlertDialog.Builder(this);

Here the AlertDialog on Kitkat: enter image description here

Oracle listener not running and won't start

Check that ORACLE_HOME environment variable is pointing to the correct oracle home. In my case it was changed by another software installation.

How to get a unique device ID in Swift?

For Swift 3.X Latest Working Code, Easily usage;

   let deviceID = UIDevice.current.identifierForVendor!.uuidString
   print(deviceID)

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

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

I faced this issue when I was tring to link a locally created repo with a blank repo on github. Initially I was trying git remote set-url but I had to do git remote add instead.

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

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:

http://localhost:9200/name_of_index/_mappings/document_type

and NOT

http://localhost:9200/name_of_index/document_type/_mappings

Oracle query to identify columns having special characters

You can use regular expressions for this, so I think this is what you want:

select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')

Multiple Image Upload PHP form with one input

<?php
if(isset($_POST['btnSave'])){
    $j = 0; //Variable for indexing uploaded image 

    $file_name_all="";

    $target_path = "uploads/"; //Declaring Path for uploaded images

    //loop to get individual element from the array
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 
        $file_extension = end($ext); //store extensions in the variable
        $basename=basename($_FILES['file']['name'][$i]);
        //echo"hi its base name".$basename;
        $target_path = $target_path .$basename;//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array       

        if (($_FILES["file"]["size"][$i] < (1024*1024)) //Approx. 100kb files can be uploaded.
        && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
                /***********************************************/

                $file_name_all.=$target_path."*";  
                $filepath = rtrim($file_name_all, '*');  
                //echo"<img src=".$filepath."   >";          

                /*************************************************/
            } else {//if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
    $qry="INSERT INTO `eb_re_about_us`(`er_abt_us_id`, `er_cli_id`, `er_cli_abt_info`, `er_cli_abt_img`) VALUES (NULL,'$b1','$b5','$filepath')";


    $res = mysql_query($qry,$conn); 
    if($res)
        echo "<br/><br/>Client contact Person Information Details Saved successfully";
        //header("location: nextaddclient.php");
        //exit();
    else
        echo "<br/><br/>Client contact Person Information Details not saved successfully";

}
?>

Here $file_name_all And $filepath get 1 uplode file name 2 time?

Why am I getting a "401 Unauthorized" error in Maven?

I had the same error. I tried and rechecked everything. I was so focused in the Stack trace that I didn't read the last lines of the build before the Reactor summary and the stack trace:

[DEBUG] Using connector AetherRepositoryConnector with priority 3.4028235E38 for http://www:8081/nexus/content/repositories/snapshots/
[INFO] Downloading: http://www:8081/nexus/content/repositories/snapshots/com/wdsuite/com.wdsuite.server.product/1.0.0-SNAPSHOT/maven-metadata.xml
[DEBUG] Could not find metadata com.group:artifact.product:version-SNAPSHOT/maven-metadata.xml in nexus (http://www:8081/nexus/content/repositories/snapshots/)
[DEBUG] Writing tracking file /home/me/.m2/repository/com/group/project/version-SNAPSHOT/resolver-status.properties
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.zip
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.pom
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:

This was the key : "Could not find metadata". Although it said that it was an authentication error actually it got fixed doing a "rebuild metadata" in the nexus repository.

Hope it helps.

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

How to Correctly handle Weak Self in Swift Blocks with Arguments

From Swift 5.3, you do not have to unwrap self in closure if you pass [self] before in in closure.

Refer someFunctionWithEscapingClosure { [self] in x = 100 } in this swift doc

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My problem was took IBOutlet but didn't connect with interface builder and using in swift file.

Remove a folder from git tracking

From the git documentation:

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:

$ git rm --cached readme.txt

So maybe don't include the "-r"?

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

Can't update: no tracked branch

I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:

git fetch

which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.

Get nth character of a string in Swift programming language

In order to feed the subject and show swift subscript possibilities, here's a little string "substring-toolbox" subscript based

These methods are safe and never go over string indexes

extension String {
    // string[i] -> one string char
    subscript(pos: Int) -> String { return String(Array(self)[min(self.length-1,max(0,pos))]) }

    // string[pos,len] -> substring from pos for len chars on the left
    subscript(pos: Int, len: Int) -> String { return self[pos, len, .pos_len, .left2right] }

    // string[pos, len, .right2left] -> substring from pos for len chars on the right
    subscript(pos: Int, len: Int, way: Way) -> String { return self[pos, len, .pos_len, way] }

    // string[range] -> substring form start pos on the left to end pos on the right
    subscript(range: Range<Int>) -> String { return self[range.startIndex, range.endIndex, .start_end, .left2right] }

    // string[range, .right2left] -> substring start pos on the right to end pos on the left
    subscript(range: Range<Int>, way: Way) -> String { return self[range.startIndex, range.endIndex, .start_end, way] }

    var length: Int { return countElements(self) }
    enum Mode { case pos_len, start_end }
    enum Way { case left2right, right2left }
    subscript(var val1: Int, var val2: Int, mode: Mode, way: Way) -> String {
        if mode == .start_end {
            if val1 > val2 { let val=val1 ; val1=val2 ; val2=val }
            val2 = val2-val1
        }
        if way == .left2right {
            val1 = min(self.length-1, max(0,val1))
            val2 = min(self.length-val1, max(1,val2))
        } else {
            let val1_ = val1
            val1 = min(self.length-1, max(0, self.length-val1_-val2 ))
            val2 = max(1, (self.length-1-val1_)-(val1-1) )
        }
        return self.bridgeToObjectiveC().substringWithRange(NSMakeRange(val1, val2))

        //-- Alternative code without bridge --
        //var range: Range<Int> = pos...(pos+len-1)
        //var start = advance(startIndex, range.startIndex)
        //var end = advance(startIndex, range.endIndex)
        //return self.substringWithRange(Range(start: start, end: end))
    }
}


println("0123456789"[3]) // return "3"

println("0123456789"[3,2]) // return "34"

println("0123456789"[3,2,.right2left]) // return "56"

println("0123456789"[5,10,.pos_len,.left2right]) // return "56789"

println("0123456789"[8,120,.pos_len,.right2left]) // return "01"

println("0123456789"[120,120,.pos_len,.left2right]) // return "9"

println("0123456789"[0...4]) // return "01234"

println("0123456789"[0..4]) // return "0123"

println("0123456789"[0...4,.right2left]) // return "56789"

println("0123456789"[4...0,.right2left]) // return "678" << because ??? range can wear endIndex at 0 ???

How to run only one task in ansible playbook?

You should use tags: as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html


If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.

Both plays and tasks support a “tags:” attribute for this reason.

Example:

tasks:

    - yum: name={{ item }} state=installed
      with_items:
         - httpd
         - memcached
      tags:
         - packages

    - template: src=templates/src.j2 dest=/etc/foo.conf
      tags:
         - configuration

If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:

ansible-playbook example.yml --tags "configuration,packages"

On the other hand, if you want to run a playbook without certain tasks, you could do this:

ansible-playbook example.yml --skip-tags "notification"

You may also apply tags to roles:

roles:
  - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }

And you may also tag basic include statements:

- include: foo.yml tags=web,foo

Both of these have the function of tagging every single task inside the include statement.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Remove your Gemfile.lock.

Move to bash if you are using zsh.

sudo bash
gem update --system 

Now run command bundle to create a new Gemfile.lock file. Move back to your zsh sudo exec zsh now run your rake commands.

SQL Server: use CASE with LIKE

You can also do like this

select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end  +  ' %'

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

This looks like undesirable behavior on github's part, but it's fairly easy to fix. What you want to do is to rebase your branch on a reasonable (any reasonable) commit in the existing history. What you can do is to fetch the github repo and find which tree in its history is most similar to the one you started with. Start this way:

git remote add github u://r/l
git fetch github

myroot=`git rev-list master --max-parents=0`
root_tree=`git rev-parse $myroot^{tree}`

github_base=`git log --pretty=%H\ %T github/master | sed -n "s/$root_tree//p"`

With any luck, that will find you a commit in the github history that has the exact tree you started with. Assuming it does,

git rebase --onto $github_base $myroot master 

and you're done.


If that doesn't find a matching tree, you get to find a nearest approximation. Here's one way to get a rough estimate of the differences:

git log --pretty='echo %H $(git diff-tree -p -b -U0 '$myroot:' %T|wc -l)' github/master \
| sh

which will count the lines in a minimized diff between the tree of each commit in the github/master history and your root tree. It seems reasonable to hope for a nice small difference, you could eyeball the actual diffs on it before calling that the github_base commit and doing the rebase above.


How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters
myCommand.ExecuteNonQuery();

Exploits of a Mom

(xkcd)

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

i mange to fix the issue by updating state. when you trigger find or any other query operation on the same record sate has been updated with modified so we need to set status to Detached then you can fire your update change

     ActivityEntity activity = new ActivityEntity();
      activity.name="vv";
    activity.ID = 22 ; //sample id
   var savedActivity = context.Activities.Find(22);

            if (savedActivity!=null)
            {
                context.Entry(savedActivity).State = EntityState.Detached;
                context.SaveChanges();

                activity.age= savedActivity.age;
                activity.marks= savedActivity.marks; 

                context.Entry(activity).State = EntityState.Modified;
                context.SaveChanges();
                return activity.ID;
            }

Transparent scrollbar with css

Embed this code in your css.

::-webkit-scrollbar {
    width: 0px;
}

/* Track */

::-webkit-scrollbar-track {
    -webkit-box-shadow: none;
}

/* Handle */

::-webkit-scrollbar-thumb {
    background: white;
    -webkit-box-shadow: none;
}

::-webkit-scrollbar-thumb:window-inactive {
    background: none;
}

Java balanced expressions check {[()]}

It's important to use a stack to push opening symbols onto it, then when you come across a closing brace you pop the element off the top of the stack and then you check it to see if it matches the type of closing brace. Here is a java implementation.

import java.util.Stack;

public class Balanced {
    public static void main (String [] args)
    {
        String test_good = "()(){}{}{()}";
        String test_bad = "((({}{}))()";

        System.out.println(checkBalanced(test_good));
        System.out.println(checkBalanced(test_bad));
    }

    public static boolean checkBalanced(String check)
    {
        Stack<Character> S = new Stack<Character>();
        for(int a = 0; a < check.length(); a++)
        {
            char let = check.charAt(a);
            if(let == '[' || let == '{' || let == '(')
                S.push(let);
            else if(let == ']' || let == '}' || let == ')')
            {
                if(S.empty())
                    return false;
                switch(let)
                {
                    // Opening square brace
                    case ']':
                        if (S.pop() != '[')
                            return false;
                        break;
                    // Opening curly brace
                    case '}':
                        if (S.pop() != '{')
                            return false;
                        break;
                    // Opening paren brace
                    case ')':
                        if (S.pop() != '(')
                            return false;
                        break;
                    default:
                        break;
                }
            }
        }
        if(S.empty())
            return true;
        return false;
    }
}

bad operand types for binary operator "&" java

== has higher precedence than &. You might want to wrap your operations in () to specify how you want your operands to bind to the operators.

((a[0] & 1) == 0)

Similarly for all parts of the if condition.

"Cannot update paths and switch to branch at the same time"

If you have a typo in your branchname you'll get this same error.

How to skip the OPTIONS preflight request?

The preflight is being triggered by your Content-Type of application/json. The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.

If you are still seeing a preflight after making this change, then Angular may be adding an X-header to the request as well.

Or you might have headers (Authorization, Cache-Control...) that will trigger it, see:

Filter rows which contain a certain string

Solution

It is possible to use str_detect of the stringr package included in the tidyverse package. str_detect returns True or False as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr package.

library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1     ? purrr   0.2.4
# ? tibble  1.4.2     ? dplyr   0.7.4
# ? tidyr   0.7.2     ? stringr 1.2.0
# ? readr   1.1.1     ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

The good things about Stringr

We should use rather stringr::str_detect() than base::grepl(). This is because there are the following reasons.

  • The functions provided by the stringr package start with the prefix str_, which makes the code easier to read.
  • The first argument of the functions of stringr package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

Benchmark

The results of the benchmark test are as follows. For large dataframe, str_detect is faster.

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

Understanding the ngRepeat 'track by' expression

You can track by $index if your data source has duplicate identifiers

e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

WON'T WORK:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

but you can, if using track by $index:

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

Excel VBA Password via Hex Editor

  1. Open xls file with a hex editor.
  2. Search for DPB
  3. Replace DPB to DPx
  4. Save file.
  5. Open file in Excel.
  6. Click "Yes" if you get any message box.
  7. Set new password from VBA Project Properties.
  8. Close and open again file, then type your new password to unprotect.

Check http://blog.getspool.com/396/best-vba-password-recovery-cracker-tool-remove/

Couldn't load memtrack module Logcat Error

I had the same error. Creating a new AVD with the appropriate API level solved my problem.

Various ways to remove local Git changes

The best way is checking out the changes.

Changing the file pom.xml in a project named project-name you can do it:

git status

# modified:   project-name/pom.xml

git checkout project-name/pom.xml
git checkout master

# Checking out files: 100% (491/491), done.
# Branch master set up to track remote branch master from origin.
# Switched to a new branch 'master'

Sublime Text 3, convert spaces to tabs

Use the following command to get it solved :

autopep8 -i <filename>.py

Cannot checkout, file is unmerged

To remove tracked files (first_file.txt) from git:

git rm first_file.txt

And to remove untracked files, use:

rm -r explore_california

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I think this problem occurs when you try to access your web driver object after

1) a window has closed and you haven't yet switched to the parent

2) you switched to a window that wasn't quite ready and has been updated since you switched

waiting for the windowhandles.count to be what you're expecting doesn't take into account the page content nor does document.ready. I'm still searching for a solution to this problem

How to vertically center a container in Bootstrap?

Tested in IE, Firefox, and Chrome.

_x000D_
_x000D_
.parent-container {_x000D_
    position: relative;_x000D_
    height:100%;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
.child-container {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    transform: translate(-50%, -50%);_x000D_
}
_x000D_
<div class="parent-container">_x000D_
    <div class="child-container">_x000D_
        <h2>Header Text</h2>_x000D_
        <span>Some Text</span>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Found on https://css-tricks.com/centering-css-complete-guide/

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

Best approach to real time http streaming to HTML5 video client

This is a very common misconception. There is no live HTML5 video support (except for HLS on iOS and Mac Safari). You may be able to 'hack' it using a webm container, but I would not expect that to be universally supported. What you are looking for is included in the Media Source Extensions, where you can feed the fragments to the browser one at a time. but you will need to write some client side javascript.

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

How to JOIN three tables in Codeigniter

try this

In your model

If u want get all album data use

  function get_all_album_data() {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $query = $this->db->get ();
    return $query->result ();
 }

if u want to get specific album data use

  function get_album_data($album_id) {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $this->db->where ( 'Album.album_id', $album_id);
    $query = $this->db->get ();
    return $query->result ();
 }

Can we locate a user via user's phone number in Android?

The answer is: you can't only through sms, i have tried that approach before.

You could fetch the base station IDs, but this won't help you a lot without the location of the base station itself and this informations are really hard to retrieve from the providers.

I have looked through the 3 apps you have listed in your question:

  1. The App uses WiFi and GPRS location service, quite the same approach as Google uses on the phone. phonesavvy maybe has a base station location database or uses a database retrieved e.g. from OpenStreetMap or some similar crowd-based project.
  2. The app analyzes just the number for country code and city code. No location there.
  3. Dito.

How to refresh or show immediately in datagridview after inserting?

this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);

Converting milliseconds to minutes and seconds with Javascript

Here's my contribution if looking for

h:mm:ss

instead like I was:

function msConversion(millis) {
  let sec = Math.floor(millis / 1000);
  let hrs = Math.floor(sec / 3600);
  sec -= hrs * 3600;
  let min = Math.floor(sec / 60);
  sec -= min * 60;

  sec = '' + sec;
  sec = ('00' + sec).substring(sec.length);

  if (hrs > 0) {
    min = '' + min;
    min = ('00' + min).substring(min.length);
    return hrs + ":" + min + ":" + sec;
  }
  else {
    return min + ":" + sec;
  }
}

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

What does "Changes not staged for commit" mean

Remove dir/.../.git

works for me.

HTML5 video won't play in Chrome only

With some help from another person, we figured out it was an issue of ordering the source files within the HTML file. I learned that browsers accept the first usable format, and their seems to be an issue with the .m4v file, so I started with the .mp4, then .webm. Here's the order that works in Safari (even on my iPhone 5), Firefox, and Chrome:

<video width="100%" height="400" poster="assets/img/myVideo.jpg" controls="controls" preload="none">
      <!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 -->
      <source type="video/mp4" src="assets/vid/PhysicsEtoys.mp4" />
      <!-- WebM/VP8 for Firefox4, Opera, and Chrome -->
      <source type="video/webm" src="assets/vid/PhysicsEtoys.webm" />
       <!-- M4V for Apple -->
      <source type="video/mp4" src="assets/vid/PhysicsEtoys.m4v" />
      <!-- Ogg/Vorbis for older Firefox and Opera versions -->
      <source type="video/ogg" src="assets/vid/PhysicsEtoys.ogv" />
      <!-- Subtitles -->
      <track kind="subtitles" src="assets/vid/subtitles.srt" srclang="en" />
      <track kind="subtitles" src="assets/vid/subtitles.vtt" srclang="en" />
      <!-- Flash fallback for non-HTML5 browsers without JavaScript -->
      <object width="100%" height="400" type="application/x-shockwave-flash" data="flashmediaelement.swf">
          <param name="movie" value="flashmediaelement.swf" />
          <param name="flashvars" value="controls=true&file=assets/vid/PhysicsEtoys.mp4" />
          <!-- Image as a last resort -->
          <img src="assets/img/myVideo.jpg" width="320" height="240" title="No video playback capabilities" />
      </object>
  </video>

Now, I'll have to re-check the encoding on the m4v file (perhaps an issue of Baseline vs Main, High, etc.).

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle

Button-Radio

The idea is to choose a the radio as a button instead of the normal circle image.

Error type 3 Error: Activity class {} does not exist

For me, I tried most of the answers, and didn't work. My Android Studio version is 4.0.1. I changed my git branch to the master branch, and then returned to my own branch, and it worked. This time I could run my branch. So weird I know

How to set seekbar min and max value

There is no option to set a min or max value in seekbar , so you can use a formula here to scale your value.

Desired_value = ( progress * ( Max_value - Min_value) / 100 ) + Min_value

I have tested this formula in many examples. In your example, if the progressBar is the middle(i.e. progress = 50 ) and your Min_val and Max_val are 60 and 180 respectively, then this formula will give you the Desired_value '120'.

ImportError: numpy.core.multiarray failed to import

Try sudo pip install numpy --upgrade --ignore-installed.

It work in Mac OS 10.11.

You should close The 'Rootless' if above shell isn't work.

Install Visual Studio 2013 on Windows 7

your log files shows it is stopping on error "0x8004C000"

From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):

Setup Status
Block

Restart not required
0x80044000 [-2147205120]

Restart required
0x8004C000 [-2147172352]

Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).

bootstrap multiselect get selected values

more efficient, due to less DOM lookups:

$('#multiselect1').multiselect({
    // ...
    onChange: function() {
        var selected = this.$select.val();
        // ...
    }
});

How to create a stopwatch using JavaScript?

Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

What are the differences between git remote prune, git prune, git fetch --prune, etc

In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.

If you guys see any issues with this please let me know and I'll fix it (etc. etc.)

Save it in a file called git-rm-ntb (call it whatever) on PATH and run:

git-rm-ntb <remote1:optional> <remote2:optional> ...

clean()
{
  REMOTES="$@";
  if [ -z "$REMOTES" ]; then
    REMOTES=$(git remote);
  fi
  REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
  RBRANCHES=()
  while read REMOTE; do
    CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
    RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
  done < <(echo "$REMOTES" )
  [[ $RBRANCHES ]] || exit
  LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
  for i in "${LBRANCHES[@]}"; do
    skip=
    for j in "${RBRANCHES[@]}"; do
      [[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
    done
    [[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
  done
}

clean $@

PG::ConnectionBad - could not connect to server: Connection refused

The Homebrew package manager includes launchctl plists to start automatically. For more information run brew info postgres.

Start manually:

pg_ctl -D /usr/local/var/postgres start

Stop manually:

pg_ctl -D /usr/local/var/postgres stop

Start automatically:

"To have launchd start postgresql now and restart at login:"

brew services start postgresql

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Loading scripts after page load?

The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)

To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:

var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);

How to define object in array in Mongoose schema correctly with 2d geo index

I had a similar issue with mongoose :

fields: 
    [ '[object Object]',
     '[object Object]',
     '[object Object]',
     '[object Object]' ] }

In fact, I was using "type" as a property name in my schema :

fields: [
    {
      name: String,
      type: {
        type: String
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

To avoid that behavior, you have to change the parameter to :

fields: [
    {
      name: String,
      type: {
        type: { type: String }
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

bash "if [ false ];" returns true instead of false -- why?

A Quick Boolean Primer for Bash

The if statement takes a command as an argument (as do &&, ||, etc.). The integer result code of the command is interpreted as a boolean (0/null=true, 1/else=false).

The test statement takes operators and operands as arguments and returns a result code in the same format as if. An alias of the test statement is [, which is often used with if to perform more complex comparisons.

The true and false statements do nothing and return a result code (0 and 1, respectively). So they can be used as boolean literals in Bash. But if you put the statements in a place where they're interpreted as strings, you'll run into issues. In your case:

if [ foo ]; then ... # "if the string 'foo' is non-empty, return true"
if foo; then ...     # "if the command foo succeeds, return true"

So:

if [ true  ] ; then echo "This text will always appear." ; fi;
if [ false ] ; then echo "This text will always appear." ; fi;
if true      ; then echo "This text will always appear." ; fi;
if false     ; then echo "This text will never appear."  ; fi;

This is similar to doing something like echo '$foo' vs. echo "$foo".

When using the test statement, the result depends on the operators used.

if [ "$foo" = "$bar" ]   # true if the string values of $foo and $bar are equal
if [ "$foo" -eq "$bar" ] # true if the integer values of $foo and $bar are equal
if [ -f "$foo" ]         # true if $foo is a file that exists (by path)
if [ "$foo" ]            # true if $foo evaluates to a non-empty string
if foo                   # true if foo, as a command/subroutine,
                         # evaluates to true/success (returns 0 or null)

In short, if you just want to test something as pass/fail (aka "true"/"false"), then pass a command to your if or && etc. statement, without brackets. For complex comparisons, use brackets with the proper operators.

And yes, I'm aware there's no such thing as a native boolean type in Bash, and that if and [ and true are technically "commands" and not "statements"; this is just a very basic, functional explanation.

Apply .gitignore on an existing repository already tracking large number of files

This answer solved my problem:

First of all, commit all pending changes.

Then run this command:

git rm -r --cached .

This removes everything from the index, then just run:

git add .

Commit it:

git commit -m ".gitignore is now working"

How can I specify my .keystore file with Spring Boot and Tomcat?

If you don't want to implement your connector customizer, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer. According to the README, you only have to create your keystore, configure connector.https.*, import the library and add @ComponentScan("org.ycavatars.sboot.kit"). Then you'll have HTTPS connection.

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

Best practice multi language website

Database work:

Create Language Table ‘languages’:

Fields:

language_id(primary and auto increamented)

language_name

created_at

created_by

updated_at

updated_by

Create a table in database ‘content’:

Fields:

content_id(primary and auto incremented)

main_content

header_content

footer_content

leftsidebar_content

rightsidebar_content

language_id(foreign key: referenced to languages table)

created_at

created_by

updated_at

updated_by

Front End Work:

When user selects any language from dropdown or any area then save selected language id in session like,

$_SESSION['language']=1;

Now fetch data from database table ‘content’ based on language id stored in session.

Detail may found here http://skillrow.com/multilingual-website-in-php-2/

Image.open() cannot identify image file - Python?

For whoever reaches here with the error colab PIL UnidentifiedImageError: cannot identify image file in Google Colab, with a new PIL versions, and none of the previous solutions works for him:

Simply restart the environment, your installed PIL version is probably outdated.

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

cannot load such file -- bundler/setup (LoadError)

I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.

I think that this problem from bundler versions with hosting, so please make sure that hosting bundler is the same version with your project.

Compare two different files line by line in python

I have just been faced with the same challenge, but I thought "Why programming this in Python if you can solve it with a simple "grep"?, which led to the following Python code:

import subprocess
from subprocess import PIPE

try:
  output1, errors1 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file1.txt", "c:\\file2.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  output2, errors2 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file2.txt", "c:\\file1.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  if (len(output1) + len(output2) + len(errors1) + len(errors2) > 0):
    print ("Compare result : There are differences:");
    if (len(output1) + len(output2) > 0):
      print ("  Output differences : ");
      print (output1);
      print (output2);
    if (len(errors1) + len(errors2) > 0):
      print (" Errors : ");
      print (errors1);
      print (errors2);
  else:
    print ("Compare result : Both files are equal");
except Exception as ex:
  print("Compare result : Exception during comparison");
  print(ex);
  raise;

The trick behind this is the following: grep -Fvf file1.txt file2.txt verifies if all entries in file2.txt are present in file1.txt. By doing this in both directions we can see if the content of both files are "equal". I put "equal" between quotes because duplicate lines are disregarded in this way of working.

Obviously, this is just an example: you can replace grep by any commandline file comparison tool.

Create a new file in git bash

This is a very simple to create file in git bash at first write touch then file name with extension

for example

touch filename.extension

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

If you have this listener:

    <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/>

on your server.xml, remove it and try. You can not use a keystore if you are using the APR connector

Rails 4: assets not loading in production

The default matcher for compiling files includes application.js, application.css and all non-JS/CSS files (this will include all image assets automatically) from app/assets folders including your gems:

If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array in config/initializers/assets.rb:

Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']

http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Try like this:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

Pay particular attention to the set() call's 3rd parameter. false prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data array.

The query generated by above code:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

I think what's missing here is that when you do:

>pip install .

to install a local package with a setup.py, it installs a package that is visible to all the conda envs that use the same version of python. Note I am using the conda version of pip!

e.g., if I'm using python2.7 it puts the local package here:

/usr/local/anaconda/lib/python2.7/site-packages

If I then later create a new conda env with python=2.7 (= the default):

>conda create --name new

>source activate new

And then do:

(new)>conda list    // empty - conda is not aware of any packages yet

However, if I do:

(new)>pip list      // the local package installed above is present

So in this case, conda does not know about the pip package, but the package is available to python.

However, If I instead install the local package (again using pip) after I've created (and activated) the new conda env, now conda sees it:

(new)>conda list   // sees that the package is there and was installed by pip

So I think the interaction between conda and pip has some issues - ie, using pip to install a local package from within one conda env makes that package available (but not seen via conda list) to all other conda envs of the same python version.

When do I need to do "git pull", before or after "git add, git commit"?

I think git pull --rebase is the cleanest way to set your locally recent commits on top of the remote commits which you don't have at a certain point.

So this way you don't have to pull every time you want to start making changes.

how to git commit a whole folder?

When you “add” something in Git, you add it to the staging area. When you commit, you then commit what’s in the staging area, meaning it’s possible to commit only a sub-set of changed files at any one time.

In your case, you want to add the folder to the staging area, and then just do a normal commit:

$ git add foldername
$ git commit -m 'Helpful commit message'

Powershell Log Off Remote Session

here is what i came up with. combining multiple answers

#computer list below
$computers = (
'computer1.domain.local',
'computer2.domain.local'

)
 
foreach ($Computer in $computers) {

 Invoke-Command -ComputerName $Computer -ScriptBlock { 
  Write-Host '______  '$Env:Computername
  $usertocheck = 'SomeUserName'
$sessionID = ((quser | Where-Object { $_ -match $usertocheck }) -split ' +')[2]
 

If([string]::IsNullOrEmpty($sessionID)){            
    Write-Host -ForegroundColor Yellow  "User Not Found."           
} else {            
    write-host -ForegroundColor Green  'Logging off ' $usertocheck 'Session ID' $sessionID
    logoff $sessionID    
}

 }
 }

How do I generate a SALT in Java for Salted-Hash?

Another version using SHA-3, I am using bouncycastle:

The interface:

public interface IPasswords {

    /**
     * Generates a random salt.
     *
     * @return a byte array with a 64 byte length salt.
     */
    byte[] getSalt64();

    /**
     * Generates a random salt
     *
     * @return a byte array with a 32 byte length salt.
     */
    byte[] getSalt32();

    /**
     * Generates a new salt, minimum must be 32 bytes long, 64 bytes even better.
     *
     * @param size the size of the salt
     * @return a random salt.
     */
    byte[] getSalt(final int size);

    /**
     * Generates a new hashed password
     *
     * @param password to be hashed
     * @param salt the randomly generated salt
     * @return a hashed password
     */
    byte[] hash(final String password, final byte[] salt);

    /**
     * Expected password
     *
     * @param password to be verified
     * @param salt the generated salt (coming from database)
     * @param hash the generated hash (coming from database)
     * @return true if password matches, false otherwise
     */
    boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash);

    /**
     * Generates a random password
     *
     * @param length desired password length
     * @return a random password
     */
    String generateRandomPassword(final int length);
}

The implementation:

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bouncycastle.jcajce.provider.digest.SHA3;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public final class Passwords implements IPasswords, Serializable {

    /*serialVersionUID*/
    private static final long serialVersionUID = 8036397974428641579L;
    private static final Logger LOGGER = Logger.getLogger(Passwords.class);
    private static final Random RANDOM = new SecureRandom();
    private static final int DEFAULT_SIZE = 64;
    private static final char[] symbols;

    static {
            final StringBuilder tmp = new StringBuilder();
            for (char ch = '0'; ch <= '9'; ++ch) {
                    tmp.append(ch);
            }
            for (char ch = 'a'; ch <= 'z'; ++ch) {
                    tmp.append(ch);
            }
            symbols = tmp.toString().toCharArray();
    }

    @Override public byte[] getSalt64() {
            return getSalt(DEFAULT_SIZE);
    }

    @Override public byte[] getSalt32() {
            return getSalt(32);
    }

    @Override public byte[] getSalt(int size) {
            final byte[] salt;
            if (size < 32) {
                    final String message = String.format("Size < 32, using default of: %d", DEFAULT_SIZE);
                    LOGGER.warn(message);
                    salt = new byte[DEFAULT_SIZE];
            } else {
                    salt = new byte[size];
            }
            RANDOM.nextBytes(salt);
            return salt;
    }

    @Override public byte[] hash(String password, byte[] salt) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    return md.digest();
            } catch (UnsupportedEncodingException e) {
                    final String message = String
                            .format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return new byte[0];
    }

    @Override public boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");
            Validate.notNull(hash, "Hash must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);

                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    final byte[] digest = md.digest();
                    return Arrays.equals(digest, hash);
            }catch(UnsupportedEncodingException e){
                    final String message =
                            String.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return false;


    }

    @Override public String generateRandomPassword(final int length) {

            if (length < 1) {
                    throw new IllegalArgumentException("length must be greater than 0");
            }

            final char[] buf = new char[length];
            for (int idx = 0; idx < buf.length; ++idx) {
                    buf[idx] = symbols[RANDOM.nextInt(symbols.length)];
            }
            return shuffle(new String(buf));
    }


    private String shuffle(final String input){
            final List<Character> characters = new ArrayList<Character>();
            for(char c:input.toCharArray()){
                    characters.add(c);
            }
            final StringBuilder output = new StringBuilder(input.length());
            while(characters.size()!=0){
                    int randPicker = (int)(Math.random()*characters.size());
                    output.append(characters.remove(randPicker));
            }
            return output.toString();
    }
}

The test cases:

public class PasswordsTest {

    private static final Logger LOGGER = Logger.getLogger(PasswordsTest.class);

    @Before
    public void setup(){
            BasicConfigurator.configure();
    }

    @Test
    public void testGeSalt() throws Exception {

            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt(0);
            int arrayLength = bytes.length;

            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testGeSalt32() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt32();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(32));
    }

    @Test
    public void testGeSalt64() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt64();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testHash() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] hash = passwords.hash("holacomoestas", passwords.getSalt64());
            assertThat("Array is not null", hash, Matchers.notNullValue());
    }


    @Test
    public void testSHA3() throws UnsupportedEncodingException {
            SHA3.DigestSHA3 md = new SHA3.Digest256();
            md.update("holasa".getBytes("UTF-8"));
            final byte[] digest = md.digest();
             assertThat("expected digest is:",digest,Matchers.notNullValue());
    }

    @Test
    public void testIsExpectedPasswordIncorrect() throws Exception {

            String password = "givemebeer";
            IPasswords passwords = new Passwords();

            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.

            final boolean isPasswordCorrect = passwords.isExpectedPassword("jfjdsjfsd", salt64, hash);

            assertThat("Password is not correct", isPasswordCorrect, is(false));

    }

    @Test
    public void testIsExpectedPasswordCorrect() throws Exception {
            String password = "givemebeer";
            IPasswords passwords = new Passwords();
            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.
            final boolean isPasswordCorrect = passwords.isExpectedPassword("givemebeer", salt64, hash);
            assertThat("Password is correct", isPasswordCorrect, is(true));
    }

    @Test
    public void testGenerateRandomPassword() throws Exception {
            IPasswords passwords = new Passwords();
            final String randomPassword = passwords.generateRandomPassword(10);
            LOGGER.info(randomPassword);
            assertThat("Random password is not null", randomPassword, Matchers.notNullValue());
    }
}

pom.xml (only dependencies):

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.1.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.51</version>
        <type>jar</type>
    </dependency>


    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>


</dependencies>

Nested ifelse statement

If the data set contains many rows it might be more efficient to join with a lookup table using data.table instead of nested ifelse().

Provided the lookup table below

lookup
     idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

and a sample data set

library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
                 idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
      idnat     idbp
 1:  french   colony
 2:  french   colony
 3:  french overseas
 4: foreign  foreign
 5:  french mainland
 6: foreign  foreign
 7: foreign  foreign
 8:  french overseas
 9:  french overseas
10:  french mainland

then we can do an update while joining:

DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
      idnat     idbp   idnat2
 1:  french   colony overseas
 2:  french   colony overseas
 3:  french overseas overseas
 4: foreign  foreign  foreign
 5:  french mainland mainland
 6: foreign  foreign  foreign
 7: foreign  foreign  foreign
 8:  french overseas overseas
 9:  french overseas overseas
10:  french mainland mainland

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Custom Date Format for Bootstrap-DatePicker

I solve it editing the file bootstrap-datapicker.js.

Look for the text bellow in the file and edit the variable "Format:"

var defaults = $.fn.datepicker.defaults = {
    assumeNearbyYear: false,
    autoclose: false,
    beforeShowDay: $.noop,
    beforeShowMonth: $.noop,
    beforeShowYear: $.noop,
    beforeShowDecade: $.noop,
    beforeShowCentury: $.noop,
    calendarWeeks: false,
    clearBtn: false,
    toggleActive: false,
    daysOfWeekDisabled: [],
    daysOfWeekHighlighted: [],
    datesDisabled: [],
    endDate: Infinity,
    forceParse: true,
    format: 'dd/mm/yyyy',
    keyboardNavigation: true,
    language: 'en',
    minViewMode: 0,
    maxViewMode: 4,
    multidate: false,
    multidateSeparator: ',',
    orientation: "auto",
    rtl: false,
    startDate: -Infinity,
    startView: 0,
    todayBtn: false,
    todayHighlight: false,
    weekStart: 0,
    disableTouchKeyboard: false,
    enableOnReadonly: true,
    showOnFocus: true,
    zIndexOffset: 10,
    container: 'body',
    immediateUpdates: false,
    title: '',
    templates: {
        leftArrow: '&laquo;',
        rightArrow: '&raquo;'
    }
};

How to bring back "Browser mode" in IE11?

You can get this using Emulation (Ctrl + 8) Document mode (10,9,8,7,5), Browser Profile (Desktop, Windows Phone)

enter image description here

How to use Tomcat 8 in Eclipse?

The latest version of Springsource STS (3.6) supports Tomcat 8. It is based on eclipse Luna 4.4 and supports Java 8. Have at it!

Allow anything through CORS Policy

I've your same requirements on a public API for which I used rails-api.

I've also set header in a before filter. It looks like this:

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

It seems you missed the Access-Control-Request-Method header.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Check your JNI/native code. One of my references was null, but it was intermittent, so it wasn't very obvious.

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

How to print a list with integers without the brackets, commas and no quotes?

Something like this should do it:

for element in list_:
   sys.stdout.write(str(element))

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

How to get current location in Android

First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

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

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

For GPS based location, this one

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Simulate a click on 'a' element using javascript/jquery

Try adding a function inside the click() method.

$('#gift-close').click(function(){
  //do something here
});

It worked for me with a function assigned inside the click() method rather than keeping it empty.

How can I match a string with a regex in Bash?

shopt -s nocasematch

if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
 then exit 0 
fi

pip cannot install anything

Your system clock is likely set in the past.Check the time using the date command and set it right

The following untracked working tree files would be overwritten by merge, but I don't care

The problem is when we have incoming changes that will merge untracked file, git complains. These commands helped me:

git clean -dxf
git pull origin master

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Android studio Gradle build speed up

For faster builds, increase the maximum heap size for the Gradle daemon to more than 2048 MB.

To do this set
org.gradle.jvmargs=-Xmx2048M
in the project gradle.properties.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Undo git update-index --assume-unchanged <file>

git update-index function has several option you can find typing as below:

git update-index --help

Here you will find various option - how to handle with the function update-index.

[if you don't know the file name]

git update-index --really-refresh 

[if you know the file name ]

git update-index --no-assume-unchanged <file>

will revert all the files those have been added in ignore list through.

git update-index --assume-unchanged <file>

SeekBar and media player in android

Based on previous statements, for better performance, you can also add an if condition

if (player.isPlaying() {
    handler.postDelayed(..., 1000);
}

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

Change Circle color of radio button

For those who want to change disable, checked and enabled states you cat do the following steps:

<!-- Or androidX radio button or material design radio button -->
<android.support.v7.widget.AppCompatRadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:buttonTint="@color/black"
                    android:text="Radiobutton1"
                    app:buttonTint="@color/radio_button_color" />

then in color res folder make a file named "radio_button_color.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/yellow900" android:state_selected="true" />
    <item android:color="@color/yellow800" android:state_checked="true" />
    <item android:color="@color/gray800" android:state_enabled="false" />
    <item android:color="@color/yellow800" android:state_enabled="true" />
</selector>

Using curl POST with variables defined in bash script functions

Putting data into a txt file worked for me

bash --version
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
curl --version
curl 7.29.0 (x86_64-redhat-linux-gnu)
 cat curl_data.txt 
 {  "type":"index-pattern", "excludeExportDetails": true  }

curl -X POST http://localhost:30560/api/saved_objects/_export -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d "$(cat curl_data.txt)" -o out.json

expand/collapse table rows with JQuery

A JavaScript accordion does the trick.

This fiddle by W3Schools makes a simple task even more simple using nothing but javascript, which i partially reproduce below.

<head>
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    font-size: 15px;
    cursor: pointer;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd; 
}

div.panel {
    padding: 0 18px;
    display: none;
    background-color: white;
}

div.panel.show {
    display: block;
}
</style>
</head><body>
<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  }
}
</script>
...
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet</p>
</div>
...
<button class="accordion">Table</button>
<div class="panel">
  <p><table name="detail_table">...</table></p>
</div>
...
<button class="accordion"><table name="button_table">...</table></button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet</p>
  <table name="detail_table">...</table>
  <img src=...></img>
</div>
...
</body></html>

if using php, don't forget to convert " to '. You can also use tables of data inside the button and it will still work.

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

Git push hangs when pushing to Github?

I had the same problem. All the git commands accessing remote git repository are hanging. I forgot that I changed my VM network settings. Once I changed it back to NAT (as before) then they started working. It is not an issue with the git but with the network itself.

How to declare std::unique_ptr and what is the use of it?

There is no difference in working in both the concepts of assignment to unique_ptr.

int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);

is similar to

unique_ptr<int> uptr (new int(3));

Here unique_ptr automatically deletes the space occupied by uptr.


how pointers, declared in this way will be different from the pointers declared in a "normal" way.

If you create an integer in heap space (using new keyword or malloc), then you will have to clear that memory on your own (using delete or free respectively).

In the below code,

int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;

Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.

In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope. So, you need not do delete or free for unique_ptr.

Parenthesis/Brackets Matching using Stack algorithm

public static boolean isBalanced(String s) {
    Map<Character, Character> openClosePair = new HashMap<Character, Character>();
    openClosePair.put('(', ')');
    openClosePair.put('{', '}');
    openClosePair.put('[', ']'); 

    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < s.length(); i++) {

        if (openClosePair.containsKey(s.charAt(i))) {
            stack.push(s.charAt(i));

        } else if ( openClosePair.containsValue(s.charAt(i))) {
            if (stack.isEmpty())
                return false;
            if (openClosePair.get(stack.pop()) != s.charAt(i))
                return false;
        }

        // ignore all other characters

    }
    return stack.isEmpty();
}

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

jQuery - Add ID instead of Class

Try this:

$('element').attr('id', 'value');

So it becomes;

$(function() {
    $('span .breadcrumb').each(function(){
        $('#nav').attr('id', $(this).text());
        $('#container').attr('id', $(this).text());
        $('.stretch_footer').attr('id', $(this).text())
        $('#footer').attr('id', $(this).text());
    });
});

So you are changing/overwriting the id of three elements and adding an id to one element. You can modify as per you needs...

Create SQLite database in android

To understand how to use sqlite database in android with best practices see - Android with sqlite database

There are few classes about which you should know and those will help you model your tables and models i.e android.provider.BaseColumns

Below is an example of a table

public class ProductTable implements BaseColumns {
  public static final String NAME = "name";
  public static final String PRICE = "price";
  public static final String TABLE_NAME = "products";

  public static final String CREATE_QUERY = "create table " + TABLE_NAME + " (" +
      _ID + " INTEGER, " +
      NAME + " TEXT, " +
      PRICE + " INTEGER)";

  public static final String DROP_QUERY = "drop table " + TABLE_NAME;
  public static final String SElECT_QUERY = "select * from " + TABLE_NAME;
}

How to add new contacts in android

There are several good articles on the subject on dev2qa.com site, about Contacts Provider API:

How To Add Contact In Android Programmatically

How To Update Delete Android Contacts Programmatically

How To Get Contact List In Android Programmatically

Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure

Official Google documentation on Contacts Provider here

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

SQL Insert into table only if record doesn't exist

This might be a simple solution to achieve this:

INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
  FROM dual
 WHERE NOT EXISTS (SELECT 1 
                     FROM funds 
                    WHERE ID = 23
                      AND date = DATE('2013-02-12'));

p.s. alternatively (if ID a primary key):

 INSERT INTO funds (ID, date, price)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need

see this Fiddle.

VLook-Up Match first 3 characters of one column with another column

Something neat...

I wanted to look up an "Exact Town ID" based on a "Partial Exact Town Name" BUT although I had the entire town name I was searching against a list of Partial town names. So I First found the "Exact Town Name" based on the part (which was actually a partial name since the "master list" is partial names unfortunately)... THEN searched for the "Exact Town ID" based on that Exact town name SO all my Vlookups/Index/Match-whatevers....were set to EXACT ....

=INDEX(county_cheatsheet!$E$1:$E$516,MATCH(VLOOKUP(LEFT(D3,3)&"*",county_cheatsheet!$E$1:$E$516,1,FALSE),county_cheatsheet!$E$1:E$516,0))

The lookup of the "first three letters of the partial town name against the list of partial town names is the MATCH(VLOOKUP(LEFT(D3,3)&"*" part

How to check if a variable is an integer or a string?

Depending on your definition of shortly, you could use one of the following options:

Table Naming Dilemma: Singular vs. Plural Names

I stick with singular for table names and any programming entity.

The reason? The fact that there are irregular plurals in English like mouse ? mice and sheep ? sheep. Then, if I need a collection, i just use mouses or sheeps, and move on.

It really helps the plurality stand out, and I can easily and programatically determine what the collection of things would look like.

So, my rule is: everything is singular, every collection of things is singular with an s appended. Helps with ORMs too.

How to change FontSize By JavaScript?

span.style.fontSize = "25px";

use this

Caching a jquery ajax response in javascript/browser

Old question, but my solution is a bit different.

I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.

The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.

To implement all you need to do is include the plugin in your page, which is here.

There are two options:

jSQL.xhrCache.max_time = 60;

Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.

jSQL.xhrCache.logging = true;

When set to true, mock XHR calls will be shown in the console for debugging.

You can clear the cache on any given page via

jSQL.tables = {}; jSQL.persist();

Print the data in ResultSet along with column names

ResultSet resultSet = statement.executeQuery("SELECT * from foo");
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
    for (int i = 1; i <= columnsNumber; i++) {
        if (i > 1) System.out.print(",  ");
        String columnValue = resultSet.getString(i);
        System.out.print(columnValue + " " + rsmd.getColumnName(i));
    }
    System.out.println("");
}

Reference : Printing the result of ResultSet

How do you format a Date/Time in TypeScript?

Update (2020)

As pointed by @jonhF in the comments, MomentJs recommends to not use MomentJs anymore. Check https://momentjs.com/docs/

Instead, I'm keeping this list with my personal TOP 3 js date libraries for future reference.

Old comment

I suggest you to use MomentJS

With moment you can have lot of outputs, and this one 09/11/2015 16:16 is one of then.

How do I add python3 kernel to jupyter (IPython)

I was getting same error with python-2. I wanted to run python-2 jupyter notebook session but by default I was getting python-3. So easiest work around is open Anaconda terminal for python-2 and type 'jupyter notebook' , it will launch jupyter-notebook session without any problem. Similary it could be tried with python-3

iPhone: Setting Navigation Bar Title

I guess you need a dynamic title that is why you don't set it in IB.

And I presume your viewController object is the one specified in the NIB?

Perhaps trying setting it to a dummy value in IB and then debug the methods to see which controller has the dummy value - assuming it appears as the title...

Child inside parent with min-height: 100% not inheriting height

Just to keep this subject complete, I found a solution not explored Here using Fixed position.

No Overflow

_x000D_
_x000D_
html, body, .wrapper, .parent, .child {_x000D_
  position: fixed;_x000D_
  top: 0; _x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  overflow: auto;_x000D_
  background: gray;_x000D_
}_x000D_
_x000D_
.height-50 {_x000D_
  height: 50%;_x000D_
  width: 5em;_x000D_
  margin: 10px auto;_x000D_
  background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="parent">_x000D_
    <div class="child">_x000D_
      _x000D_
      <div class="height-50"></div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

With Overflow

_x000D_
_x000D_
html, body, .wrapper, .parent, .child {_x000D_
  position: fixed;_x000D_
  top: 0; _x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  overflow: auto;_x000D_
  background: gray;_x000D_
}_x000D_
_x000D_
.height-150 {_x000D_
  height: 150%;_x000D_
  width: 5em;_x000D_
  margin: 10px auto;_x000D_
  background: cyan;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="parent">_x000D_
    <div class="child">_x000D_
      _x000D_
      <div class="height-150"></div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

How to unnest a nested list

Use itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

How do I concatenate strings with variables in PowerShell?

Try the Join-Path cmdlet:

Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
    Join-Path -Path  $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)" 
}

Reset AutoIncrement in SQL Server after Delete

DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

if number=0 then in the next insert the auto increment field will contain value 1

if number=101 then in the next insert the auto increment field will contain value 102


Some additional info... May be useful to you

Before giving auto increment number in above query, you have to make sure your existing table's auto increment column contain values less that number.

To get the maximum value of a column(column_name) from a table(table1), you can use following query

 SELECT MAX(column_name) FROM table1

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

What are .dex files in Android?

About the .dex File :

One of the most remarkable features of the Dalvik Virtual Machine (the workhorse under the Android system) is that it does not use Java bytecode. Instead, a homegrown format called DEX was introduced and not even the bytecode instructions are the same as Java bytecode instructions.

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created by automatically translating compiled applications written in the Java programming language.

Dex file format:

 1. File Header
 2. String Table
 3. Class List
 4. Field Table
 5. Method Table
 6. Class Definition Table
 7. Field List
 8. Method List
 9. Code Header
10. Local Variable List

Android has documentation on the Dalvik Executable Format (.dex files). You can find out more over at the official docs: Dex File Format

.dex files are similar to java class files, but they were run under the Dalkvik Virtual Machine (DVM) on older Android versions, and compiled at install time on the device to native code with ART on newer Android versions.

You can decompile .dex using the dexdump tool which is provided in android-sdk.

There are also some Reverse Engineering Techniques to make a jar file or java class file from a .dex file.

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

Calculate percentage Javascript

You can use this

function percentage(partialValue, totalValue) {
   return (100 * partialValue) / totalValue;
} 

Example to calculate the percentage of a course progress base in their activities.

const totalActivities = 10;
const doneActivities = 2;

percentage(doneActivities, totalActivities) // Will return 20 that is 20%

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

Adding new line of data to TextBox

C# - serialData is ReceivedEventHandler in TextBox.

SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();

serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));

Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.

Serial:

Serial.print(rnd);
Serial.( '\n' );  //carriage return

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

How can I convert integer into float in Java?

You just need to cast at least one of the operands to a float:

float z = (float) x / y;

or

float z = x / (float) y;

or (unnecessary)

float z = (float) x / (float) y;

How to check not in array element

$id = $access_data['Privilege']['id']; 

if(!in_array($id,$user_access_arr));
    $user_access_arr[] = $id;
    $this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
    return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));

Detect all Firefox versions in JS

This script detects all versions of Firefox, for Desktop, from version 1 to 46.

It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.

I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.

_x000D_
_x000D_
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
    // Match UserAgent string with Firefox Desktop_x000D_
    // Detect hybrid Gecko browsers and mobile_x000D_
    if (navigator.userAgent.match(/firefox/i) &&_x000D_
        !navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
        // Create Element and Array to test availability  _x000D_
        var createdElement = document.createElement('div'),_x000D_
            createdArray = [],_x000D_
            firefoxVersion = "0";_x000D_
_x000D_
        // Firefox 1.0 released November 9, 2004 _x000D_
        // Check a current feature as being true, or NOT undefined _x000D_
        // AND check future features as EQUAL undefined_x000D_
        if (typeof window.alert !== "undefined" &&_x000D_
            typeof window.XPCNativeWrapper === "undefined" &&_x000D_
            typeof window.URL === "undefined") {_x000D_
            firefoxVersion = "1";_x000D_
        }_x000D_
_x000D_
        // Firefox 1.5 released October 15, 2003 _x000D_
        // XPCNativeWrapper used to create security wrapper_x000D_
        else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
            typeof window.globalStorage === "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "1.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 2 released October 24, 2006_x000D_
        // globalStorage later deprecated in favor of localstorage_x000D_
        else if (typeof window.globalStorage !== "undefined" &&_x000D_
            typeof window.postMessage === "undefined") {_x000D_
            firefoxVersion = "2";_x000D_
        }_x000D_
_x000D_
        // Firefox 3 released June 17, 2008_x000D_
        // postMessage for cross window messaging_x000D_
        else if (typeof window.postMessage !== "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "3";_x000D_
        }_x000D_
_x000D_
        // Firefox 3.5 released June 30, 2009_x000D_
        // querySelector returns list of the elements from document_x000D_
        else if (typeof document.querySelector !== "undefined" &&_x000D_
            typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "3.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 4 released March 22, 2011_x000D_
        // window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
        else if (typeof window.URL !== "undefined" &&_x000D_
            typeof createdElement.style.MozAnimation === "undefined") {_x000D_
            firefoxVersion = "4";_x000D_
        }_x000D_
_x000D_
        // After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
        // Firefox 5 released June 21, 2011_x000D_
        // style.MozAnimation for CSS animation, renamed to style.animation_x000D_
        else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
            typeof WeakMap === "undefined") {_x000D_
            firefoxVersion = "5";_x000D_
        }_x000D_
_x000D_
        // Firefox 6 released August 16, 2011_x000D_
        // WeakMap collects key value pairs weakly referenced_x000D_
        else if (typeof WeakMap !== "undefined" &&_x000D_
            typeof createdElement.style.textOverflow === "undefined") {_x000D_
            firefoxVersion = "6";_x000D_
        }_x000D_
_x000D_
        // Firefox 7 released September 27, 2011_x000D_
        // textOverflow manages overflowed non displayed content_x000D_
        else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
            typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
            firefoxVersion = "7";_x000D_
        }_x000D_
_x000D_
        // Firefox 8 released November 8, 2011_x000D_
        // insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
        // faster than direct innerHTML manipulation and_x000D_
        // appends without affecting other elements under the same parent_x000D_
        else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
            typeof navigator.doNotTrack === "undefined") {_x000D_
            firefoxVersion = "8";_x000D_
        }_x000D_
_x000D_
        // Firefox 9 released December 20, 2011_x000D_
        // mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
        // IndexDB improved functionality than localstorage_x000D_
        else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
            typeof document.mozFullScreenEnabled === "undefined") {_x000D_
            firefoxVersion = "9";_x000D_
        }_x000D_
_x000D_
        // Firefox 10 released January 31, 2012_x000D_
        // mozFullScreenEnabled reports if full-screen mode is available_x000D_
        else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
            typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "10";_x000D_
        }_x000D_
_x000D_
        // Firefox 11 released March 13, 2012_x000D_
        // mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
        // Cancels an animation frame request_x000D_
        else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
            typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
            firefoxVersion = "11";_x000D_
        }_x000D_
_x000D_
        // Firefox 12 released April 24, 2012_x000D_
        // MozTextAlignLast how the last line is aligned_x000D_
        else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
            typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
            firefoxVersion = "12";_x000D_
        }_x000D_
_x000D_
        // Firefox 13 released June 5, 2012_x000D_
        // MozOpacity dropped from this version_x000D_
        else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
            typeof window.globalStorage !== "undefined") {_x000D_
            firefoxVersion = "13";_x000D_
        }_x000D_
_x000D_
        // Firefox 14 released June 26, 2012_x000D_
        // globalStorage dropped from this version_x000D_
        else if (typeof window.globalStorage === "undefined" &&_x000D_
            typeof createdElement.style.borderImage === "undefined" &&_x000D_
            typeof document.querySelector !== "undefined") {_x000D_
            firefoxVersion = "14";_x000D_
        }_x000D_
_x000D_
        // Firefox 15 released August 28, 2012_x000D_
        // borderImage allows drawing an image on the borders of elements_x000D_
        else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined") {_x000D_
            firefoxVersion = "15";_x000D_
        }_x000D_
_x000D_
        // Firefox 16 released October 9, 2012_x000D_
        // animation was MozAnimation_x000D_
        else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
            typeof createdElement.style.iterator === "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "16";_x000D_
        }_x000D_
_x000D_
        // Firefox 17 released November 20, 2012_x000D_
        // version 27 drops iterator and renames italic_x000D_
        // Used to iterate over enumerable properties of an object_x000D_
        else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined") {_x000D_
            firefoxVersion = "17";_x000D_
        }_x000D_
_x000D_
        // Firefox 18 released January 8, 2013_x000D_
        // devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
        else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
            typeof window.getInterface === "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "18";_x000D_
        }_x000D_
_x000D_
        // Firefox 19 released February 19, 2013_x000D_
        // getInterface dropped and renamed in version 32_x000D_
        // Retrieves specified interface pointers_x000D_
        else if (typeof window.getInterface !== "undefined" &&_x000D_
            typeof Math.imul === "undefined") {_x000D_
            firefoxVersion = "19";_x000D_
        }_x000D_
_x000D_
        // Firefox 20 released April 2, 2013_x000D_
        // Math.imul provides fast 32 bit integer multiplication_x000D_
        else if (typeof Math.imul !== "undefined" &&_x000D_
            typeof window.crypto.getRandomValues === "undefined") {_x000D_
            firefoxVersion = "20";_x000D_
        }_x000D_
_x000D_
        // Firefox 21 released May 14, 2013_x000D_
        // getRandomValues lets you get cryptographically random values_x000D_
        else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
            typeof createdElement.style.flex === "undefined") {_x000D_
            firefoxVersion = "21";_x000D_
        }_x000D_
_x000D_
        // Firefox 22 released June 25, 2013_x000D_
        // flex can alter dimensions to fill available space_x000D_
        else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
            typeof window.cancelAnimationFrame === "undefined") {_x000D_
            firefoxVersion = "22";_x000D_
        }_x000D_
_x000D_
        // Firefox 23 released August 6, 2013_x000D_
        // cancelAnimationFrame was mozCancelAnimationFrame_x000D_
        else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "23";_x000D_
        }_x000D_
_x000D_
        // Firefox 24 released September 17, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        // loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
        else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "24";_x000D_
        }_x000D_
_x000D_
        // Firefox 25 released October 29, 2013_x000D_
        // Math.trunc returns number removing fractional digits_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined") {_x000D_
            firefoxVersion = "25";_x000D_
        }_x000D_
_x000D_
        // Firefox 26 released December 10, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "26";_x000D_
        }_x000D_
_x000D_
        // Firefox 27 released February 4, 2014_x000D_
        // Math.hypot returns square root of the sum of squares_x000D_
        else if (typeof Math.hypot !== "undefined" &&_x000D_
            typeof createdArray.entries === "undefined") {_x000D_
            firefoxVersion = "27";_x000D_
        }_x000D_
_x000D_
        // Firefox 28 released March 18, 2014_x000D_
        // entries returns key value pairs for arrays_x000D_
        else if (typeof createdArray.entries !== "undefined" &&_x000D_
            typeof createdElement.style.boxSizing === "undefined") {_x000D_
            firefoxVersion = "28";_x000D_
        }_x000D_
_x000D_
        // Firefox 29 released April 29, 2014_x000D_
        // boxSizing alters CSS box model, calculates width and height of elements_x000D_
        else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
            typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
            firefoxVersion = "29";_x000D_
        }_x000D_
_x000D_
        // Firefox 30 released June 10, 2014_x000D_
        // backgroundBlendMode blends elements background images_x000D_
        else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
            typeof createdElement.style.paintOrder === "undefined") {_x000D_
            firefoxVersion = "30";_x000D_
        }_x000D_
_x000D_
        // Firefox 31 released July 22, 2014_x000D_
        // paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
        else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "31";_x000D_
        }_x000D_
_x000D_
        // Firefox 32 released September 2, 2014_x000D_
        // mixBlendMode how an element should blend _x000D_
        else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
            typeof Number.toInteger !== "undefined") {_x000D_
            firefoxVersion = "32";_x000D_
        }_x000D_
_x000D_
        // Firefox 33 released October 14, 2014_x000D_
        // numberToIntger dropped, used to convert values to integer_x000D_
        else if (typeof Number.toInteger === "undefined" &&_x000D_
            typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
            firefoxVersion = "33";_x000D_
        }_x000D_
_x000D_
        // Firefox 34 released December 1, 2014_x000D_
        // fontFeatureSettings control over advanced typographic features_x000D_
        else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
            typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
            firefoxVersion = "34";_x000D_
        }_x000D_
_x000D_
        // Firefox 35 released January 13, 2015_x000D_
        // mozIsLocallyAvailable dropped_x000D_
        else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
            firefoxVersion = "35";_x000D_
        }_x000D_
_x000D_
        // Firefox 36 released February 24, 2015_x000D_
        // quote returns a copy of the string_x000D_
        else if (typeof String.quote !== "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
            firefoxVersion = "36";_x000D_
        }_x000D_
_x000D_
        // Firefox 37 released March 31, 2015_x000D_
        // quote quickly dropped_x000D_
        else if (typeof String.quote === "undefined" &&_x000D_
            typeof createdElement.style.rubyPosition === "undefined") {_x000D_
            firefoxVersion = "37";_x000D_
        }_x000D_
_x000D_
        // Firefox 38 released May 12, 2015_x000D_
        // rubyPosition defines position of a ruby element relative to its base element_x000D_
        else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
            typeof window.Headers === "undefined") {_x000D_
            firefoxVersion = "38";_x000D_
        }_x000D_
_x000D_
        // Firefox 39 released July 2, 2015_x000D_
        // Headers allows us to create our own headers objects _x000D_
        else if (typeof window.Headers !== "undefined" &&_x000D_
            typeof Symbol.match === "undefined") {_x000D_
            firefoxVersion = "39";_x000D_
        }_x000D_
_x000D_
        // Firefox 40 released August 11, 2015_x000D_
        // match matches a regular expression against a string_x000D_
        else if (typeof Symbol.match !== "undefined" &&_x000D_
            typeof Symbol.species === "undefined") {_x000D_
            firefoxVersion = "40";_x000D_
        }_x000D_
_x000D_
        // Firefox 41 released September 22, 2015_x000D_
        // species allows subclasses to over ride the default constructor_x000D_
        else if (typeof Symbol.species !== "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "41";_x000D_
        }_x000D_
_x000D_
        // Firefox 42 released November 3, 2015_x000D_
        // mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
        // Reflect offers methods for interceptable JavaScript operations_x000D_
        else if (typeof Reflect !== "undefined" &&_x000D_
            typeof window.screen.orientation === "undefined") {_x000D_
            firefoxVersion = "42";_x000D_
        }_x000D_
_x000D_
        // Firefox 43 released December 15, 2015_x000D_
        // orientation is mozOrientation in B2G and Android_x000D_
        else if (typeof window.screen.orientation !== "undefined" &&_x000D_
            typeof document.charset === "undefined") {_x000D_
            firefoxVersion = "43";_x000D_
        }_x000D_
_x000D_
        // Firefox 44 released January 26, 2016_x000D_
        // charset is for legacy, use document.characterSet_x000D_
        else if (typeof document.charset !== "undefined" &&_x000D_
            typeof window.onstorage === "undefined") {_x000D_
            firefoxVersion = "44";_x000D_
        }_x000D_
_x000D_
        // Firefox 45 released March 8, 2016_x000D_
        // onstorage contains an event handler that runs when the storage event fires_x000D_
        else if (typeof window.onstorage !== "undefined" &&_x000D_
            typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
            firefoxVersion = "45";_x000D_
        }_x000D_
_x000D_
        // Firefox 46 - beta_x000D_
        // onabsolutedeviceorientation_x000D_
        else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
            firefoxVersion = "46 or above";_x000D_
        }_x000D_
_x000D_
        // Else could not verify_x000D_
        else {_x000D_
            outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
        }_x000D_
_x000D_
        // Display Firefox version_x000D_
        outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
        // Else not detected_x000D_
    } else {_x000D_
        outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
    }_x000D_
} catch (e) {_x000D_
    // Statement to handle exceptions_x000D_
    outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
_x000D_
_x000D_

What is a superfast way to read large files line-by-line in VBA?

I just wanted to share some of my results...

I have text files, which apparently came from a Linux system, so I only have a vbLF/Chr(10) at the end of each line and not vbCR/Chr(13).

Note 1:

  • This meant that the Line Input method would read in the entire file, instead of just one line at a time.

From my research testing small (152KB) & large (2778LB) files, both on and off the network I found the following:

Open FileName For Input: Line Input was the slowest (See Note 1 above)

Open FileName For Binary Access Read: Input was the fastest for reading the whole file

FSO.OpenTextFile: ReadLine was fast, but a bit slower then Binary Input

Note 2:

  • If I just needed to check the file header (first 1-2 lines) to check if I had the proper file/format, then FSO.OpenTextFile was the fastest, followed very closely by Binary Input.

  • The drawback with the Binary Input is that you have to know how many characters you want to read.

  • On normal files, Line Input would also be a good option as well, but I couldn't test due to Note 1.

 

Note 3:

  • Obviously, the files on the network showed the largest difference in read speed. They also showed the greatest benefit from reading the file a second time (although there are certainly memory buffers that come into play here).

Is there a way to do repetitive tasks at intervals?

If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.

i.e.

package main

import "fmt"
import "time"

func main() {
    go heartBeat()
    time.Sleep(time.Second * 5)
}

func heartBeat() {
    for range time.Tick(time.Second * 1) {
        fmt.Println("Foo")
    }
}

Playground

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Clearing state es6 React

const initialState = {
    a: '',
    b: '',
    c: ''
};

class ExampleComponent extends Component {
    state = { ...initialState } // use spread operator to avoid mutation
    handleReset = this.handleReset.bind(this);

    handleReset() {
         this.setState(initialState);
    }
 }

Remember that in order to be able to reset the state it is important not to mutate initialState.

state = {...initialState} // GOOD 
// => state points to a new obj in memory which has the values of initialState

state = initialState // BAD 
// => they point to the same obj in memory

The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.

state = Object.assign({}, initialState); // GOOD
state = {...initialState}; // GOOD

How to run a method every X seconds

Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    t.start();

In case it needed it can be stoped by

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

Email and phone Number Validation in android

He want an elegant and proper solution try this small regex pattern matcher.

This is specifically for India.(First digit can't be zero and and then can be any 9 digits) return mobile.matches("[1-9][0-9]{9}");

Pattern Breakdown:-

[1-9] matches first digit and checks if number(integer) lies between(inclusive) 1 to 9 [0-9]{9} matches the same thing but {9} tells the pattern that it has to check for upcoming all 9 digits.

Now the {9} part may vary for different countries so you may have array which tells the number of digits allowed in phone number. Some countries also have significance for zero ahead of number, so you may have exception for those and design a separate regex patterns for those countries phone numbers.

Immutable array in Java

No, this is not possible. However, one could do something like this:

List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);

This requires using wrappers, and is a List, not an array, but is the closest you will get.

HTML list-style-type dash

You could use :before and content: bearing in mind that this is not supported in IE 7 or below. If you're OK with that then this is your best solution. See the Can I Use or QuirksMode CSS compatibility tables for full details.

A slightly nastier solution that should work in older browsers is to use an image for the bullet point and just make the image look like a dash. See the W3C list-style-image page for examples.

Export tables to an excel spreadsheet in same directory

You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.

To obtain the path of the Access database, use the CurrentProject.Path property.

To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd") method.

Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet method.

Example:

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This will output both Table1 and Table2 into the same Workbook.

HTH

How to Install Sublime Text 3 using Homebrew

brew install caskroom/cask/brew-cask
brew tap caskroom/versions
brew cask install sublime-text

Weird how I will struggle with this for days, post on StackOverflow, then figure out my own answer in 20 seconds.

[edited to reflect that the package name is now just sublime-text, not sublime-text3]

Getting the parent of a directory in Bash

Started from the idea/comment Charles Duffy - Dec 17 '14 at 5:32 on the topic Get current directory name (without full path) in a Bash script

#!/bin/bash
#INFO : https://stackoverflow.com/questions/1371261/get-current-directory-name-without-full-path-in-a-bash-script
# comment : by Charles Duffy - Dec 17 '14 at 5:32
# at the beginning :



declare -a dirName[]

function getDirNames(){
dirNr="$(  IFS=/ read -r -a dirs <<<"${dirTree}"; printf '%s\n' "$((${#dirs[@]} - 1))"  )"

for(( cnt=0 ; cnt < ${dirNr} ; cnt++))
  do
      dirName[$cnt]="$( IFS=/ read -r -a dirs <<<"$PWD"; printf '%s\n' "${dirs[${#dirs[@]} - $(( $cnt+1))]}"  )"
      #information – feedback
      echo "$cnt :  ${dirName[$cnt]}"
  done
}

dirTree=$PWD;
getDirNames;

How can I URL encode a string in Excel VBA?

The VBA-tools library has a function for that:

http://vba-tools.github.io/VBA-Web/docs/#/WebHelpers/UrlEncode

It seems to work similar to encodeURIComponent() in JavaScript.

How do I position an image at the bottom of div?

< img style="vertical-align: bottom" src="blah.png" >

Works for me. Inside a parallax div as well.

Browse files and subfolders in Python

Slightly altered version of Sven Marnach's solution..


import os

folder_location = 'C:\SomeFolderName' file_list = create_file_list(folder_location)

def create_file_list(path): return_list = []

for filenames in os.walk(path): for file_list in filenames: for file_name in file_list: if file_name.endswith((".txt")): return_list.append(file_name) return return_list

How do you do exponentiation in C?

int power(int x,int y){
 int r=1;
 do{
  r*=r;
  if(y%2)
   r*=x;
 }while(y>>=1);
 return r;
};

(iterative)

int power(int x,int y){
 return y?(y%2?x:1)*power(x*x,y>>1):1;
};

(if it has to be recursive)

imo, the algorithm should definitely be O(logn)

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

A 'for' loop to iterate over an enum in Java

we can use a filter(JAVA 8) like this.

Stream.of(Direction.values()).filter(name -> !name.toString().startsWith("S")).forEach(System.out::println);

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

Read Content from Files which are inside Zip file

If you're wondering how to get the file content from each ZipEntry it's actually quite simple. Here's a sample code:

public static void main(String[] args) throws IOException {
    ZipFile zipFile = new ZipFile("C:/test.zip");

    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()){
        ZipEntry entry = entries.nextElement();
        InputStream stream = zipFile.getInputStream(entry);
    }
}

Once you have the InputStream you can read it however you want.

command/usr/bin/codesign failed with exit code 1- code sign error

The following steps solved the problem for me. I was having the issue where it was not compiling for the device or archiving, working fine for simulator.

  1. Open keychain access.
  2. Lock the 'login' keychain.
  3. Unlock it.

Clean and build after doing the above steps and everything works fine now.

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

After 2 hrs of net surfing Finally For me the problem was fixed by creating a folder pip, with a file: pip.ini in C:\Users<username>\AppData\Roaming\ e.g:

C:\Users\<username>\AppData\Roaming\pip\pip.ini

Inside it I wrote:

[global]
trusted-host = pypi.python.org
pypi.org
files.pythonhosted.org

I restarted python, and then pip permanently trusted these sites, and used them to download packages from.

If you can't find the AppData Folder on windows, write %appdata% in file explorer and it should appear.

Source : pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

Java: Detect duplicates in ArrayList?

This answer is wrriten in Kotlin, but can easily be translated to Java.

If your arraylist's size is within a fixed small range, then this is a great solution.

var duplicateDetected = false
    if(arrList.size > 1){
        for(i in 0 until arrList.size){
            for(j in 0 until arrList.size){
                if(i != j && arrList.get(i) == arrList.get(j)){
                    duplicateDetected = true
                }
            }
        }
    }

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

Return a 2d array from a function

#include <iostream>
using namespace std ;

typedef int (*Type)[3][3] ;

Type Demo_function( Type ); //prototype

int main (){
    cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"

    int array[3][3] ;
    Type recieve , ptr = &array;
    recieve = Demo_function( ptr ) ;

    for ( int i = 0 ;  i < 3 ; i ++ ){
        for ( int j = 0 ; j < 3 ; j ++ ){
            cout <<  (*recieve)[i][j] << " " ;
        }
    cout << endl ; 
    }

return 0 ;
}


Type Demo_function( Type array ){/*function definition */

    cout << "Enter values : \n" ;
    for (int i =0 ;  i < 3 ; i ++)
        for ( int j = 0 ; j < 3 ; j ++ )
            cin >> (*array)[i][j] ;

    return array ; 
}

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Below is my code.I also had the same error but the problem was that i gave my password wrong.The below code will work perfectly..try it

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");             
            mail.From = new MailAddress("[email protected]");
            mail.To.Add("[email protected]");
            mail.To.Add("[email protected]");
            mail.Subject = "Password Recovery ";
            mail.Body += " <html>";
            mail.Body += "<body>";
            mail.Body += "<table>";
            mail.Body += "<tr>";
            mail.Body += "<td>User Name : </td><td> HAi </td>";
            mail.Body += "</tr>";

            mail.Body += "<tr>";
            mail.Body += "<td>Password : </td><td>aaaaaaaaaa</td>";
            mail.Body += "</tr>";
            mail.Body += "</table>";
            mail.Body += "</body>";
            mail.Body += "</html>";
            mail.IsBodyHtml = true;
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("sendfrommailaddress.com", "password");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);

You can refer it in my blog

Using current time in UTC as default value in PostgreSQL

What about

now()::timestamp

If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.

I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.

EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:

Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

How do I change the number of open files limit in Linux?

If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting

[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread

Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.

Getting HTTP headers with Node.js

Here is my contribution, that deals with any URL using http or https, and use Promises.

const http = require('http')
const https = require('https')
const url = require('url')

function getHeaders(myURL) {
  const parsedURL = url.parse(myURL)
  const options = {
    protocol: parsedURL.protocol,
    hostname: parsedURL.hostname,
    method: 'HEAD',
    path: parsedURL.path
  }
  let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)

  return new Promise((resolve, reject) => {
    let req = protocolHandler.request(options, (res) => {
      resolve(res.headers)
    })
    req.on('error', (e) => {
      reject(e)
    })
    req.end()
  })
}

getHeaders(myURL).then((headers) => {
  console.log(headers)
})

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

To check whether the frame have been loaded, use onload function. Or put your main function in load: I recommend to use load when creating the iframe by js

 $('<iframe />', {
   src: url,
   id:  'receiver',
   frameborder: 1,
   load:function(){
     //put your code here, so that those code can be make sure to be run after the frame loaded
   }
   }).appendTo('body');

How to validate an email address using a regular expression?

This question is asked a lot, but I think you should step back and ask yourself why you want to validate email adresses syntactically? What is the benefit really?

  • It will not catch common typos.
  • It does not prevent people from entering invalid or made-up email addresses, or entering someone else's address.

If you want to validate that an email is correct, you have no choice than to send an confirmation email and have the user reply to that. In many cases you will have to send a confirmation mail anyway for security reasons or for ethical reasons (so you cannot e.g. sign someone up to a service against their will).

What do multiple arrow functions mean in javascript?

Brief and simple

It is a function which returns another function written in short way.

const handleChange = field => e => {
  e.preventDefault()
  // Do something here
}

// is equal to 
function handleChange(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
  }
}

Why people do it ?

Have you faced when you need to write a function which can be customized? Or you have to write a callback function which has fixed parameters (arguments), but you need to pass more variables to the function but avoiding global variables? If your answer "yes" then it is the way how to do it.

For example we have a button with onClick callback. And we need to pass id to the function, but onClick accepts only one parameter event, we can not pass extra parameters within like this:

const handleClick = (event, id) {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

It will not work!

Therefore we make a function which will return other function with its own scope of variables without any global variables, because global variables are evil .

Below the function handleClick(props.id)} will be called and return a function and it will have id in its scope! No matter how many times it will be pressed the ids will not effect or change each other, they are totally isolated.

const handleClick = id => event {
  event.preventDefault()
  // Dispatch some delete action by passing record id
}

const Confirm = props => (
  <div>
    <h1>Are you sure to delete?</h1>
    <button onClick={handleClick(props.id)}>
      Delete
    </button>
  </div
)

Other benefit

A function which returns another function also called "curried functions" and they are used for function compositions.

You can find example here: https://gist.github.com/sultan99/13ef56b4089789a8d115869ee2c5ec47

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

You can take a look at this. One of the examples says:

var d = new Date(dateString);

Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.

How to change navigation bar color in iOS 7 or 6?

// In ios 7 :-

[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];

// In ios 6 :-

[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

How can I convince IE to simply display application/json rather than offer to download it?

If you are okay with just having IE open the JSON into a notepad, you can change your system's default program for .json files to Notepad.

To do this, create or find a .json file, right mouse click, and select "Open With" or "Choose Default Program."

This might come in handy if you by chance want to use Internet Explorer but your IT company wont let you edit your registry. Otherwise, I recommend the above answers.

PHP check whether property exists in object or class

To check if something exits, you can use the PHP function isset() see php.net. This function will check if the variable is set and is not NULL.

Example:

if(isset($obj->a))
{ 
  //do something
}

If you need to check if a property exists in a class, then you can use the build in function property_exists()

Example:

if (property_exists('class', $property)) {
    //do something
}

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

@Transactional(propagation=Propagation.REQUIRED)

In Spring applications, if you enable annotation based transaction support using <tx:annotation-driven/> and annotate any class/method with @Transactional(propagation=Propagation.REQUIRED) then Spring framework will start a transaction and executes the method and commits the transaction. If any RuntimeException occurred then the transaction will be rolled back.

Actually propagation=Propagation.REQUIRED is default propagation level, you don't need to explicitly mentioned it.

For further info : http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

How to delete empty folders using windows command prompt?

You can use the ROBOCOPY command. It is very simple and can also be used to delete empty folders inside large hierarchy.

ROBOCOPY folder1 folder1 /S /MOVE

Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other(required) files to different folder. /S option is to skip copying(moving - in the above case) empty folders. It is also faster as the files are moved inside the same drive.

Change keystore password from no password to a non blank password

If you're trying to do stuff with the Java default system keystore (cacerts), then the default password is changeit.

You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.

(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)

How to do a simple file search in cmd

dir /s *foo* searches in current folder and sub folders.

It finds directories as well as files.

where /s means(documentation):

/s Lists every occurrence of the specified file name within the specified directory and all subdirectories.

Simple java program of pyramid

A better pyramid can be printed this way:

The Pattern is
     $     
    $$$    
   $$$$$   
  $$$$$$$  
 $$$$$$$$$ 
$$$$$$$$$$$
public static void main(String agrs[]) {
    System.out.println("The Pattern is");
    int size = 11; //use only odd numbers here
    for (int i = 1; i <= size; i=i+2) {
        int spaceCount = (size - i)/2;
        for(int j = 0; j< size; j++) {
            if(j < spaceCount || j >= (size - spaceCount)) {
                System.out.print(" ");
            } else {
                System.out.print("$");
            }
        }
        System.out.println();
    }
}

What is the difference between ng-if and ng-show/ng-hide

ngIf

The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

<!-- when $scope.myValue is truthy (element is restored) -->
<div ng-if="1"></div>

<!-- when $scope.myValue is falsy (element is removed) -->
<div ng-if="0"></div>

When an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance.

If ngModel is used within ngIf to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="data">
</div>        

To get around this situation and update the model in the parent scope from inside the child scope, use an object:

<input type="text" ng-model="data.input">
<div ng-if="true">
    <input type="text" ng-model="data.input">
</div>

Or, $parent variable to reference the parent scope object:

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="$parent.data">
</div>

ngShow

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag).

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="1"></div>

<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="0" class="ng-hide"></div>

When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute on the element causing it to become hidden. When true, the ng-hide CSS class is removed from the element causing the element not to appear hidden.

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

To add my 2 cents, I got this same issue when I m accidentally sending null as the ID. Below code depicts my scenario (and anyway OP didn't mention any specific scenario).

Employee emp = new Employee();
emp.setDept(new Dept(deptId)); // -----> when deptId PKID is null, same error will be thrown
// calls to other setters...
em.persist(emp);

Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.

In some scenarios, deptId PKID is coming as null from calling method and I m getting the same error.

So, watch for null values for PK ID

Same answer given here

angular.service vs angular.factory

Here are the primary differences:

Services

Syntax: module.service( 'serviceName', function );

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending ( ) to the injected function reference. Could also be run with injectedArg.call( this ) or similar.

Factories

Syntax: module.factory( 'factoryName', function );

Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Usage: Could be useful for returning a 'class' function that can then be new'ed to create instances.

Here is example using services and factory. Read more about AngularJS Service vs Factory.

You can also check the AngularJS documentation and similar question on stackoverflow confused about service vs factory.

3-dimensional array in numpy

You are right, you are creating a matrix with 2 rows, 3 columns and 4 depth. Numpy prints matrixes different to Matlab:

Numpy:

>>> import numpy as np
>>> np.zeros((2,3,2))
 array([[[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]],

   [[ 0.,  0.],
    [ 0.,  0.],
    [ 0.,  0.]]])

Matlab

>> zeros(2, 3, 2)
 ans(:,:,1) =
     0     0     0
     0     0     0
 ans(:,:,2) =
     0     0     0
     0     0     0

However you are calculating the same matrix. Take a look to Numpy for Matlab users, it will guide you converting Matlab code to Numpy.


For example if you are using OpenCV, you can build an image using numpy taking into account that OpenCV uses BGR representation:

import cv2
import numpy as np

a = np.zeros((100, 100,3))
a[:,:,0] = 255

b = np.zeros((100, 100,3))
b[:,:,1] = 255

c = np.zeros((100, 200,3)) 
c[:,:,2] = 255

img = np.vstack((c, np.hstack((a, b))))

cv2.imshow('image', img)
cv2.waitKey(0)

enter image description here

If you take a look to matrix c you will see it is a 100x200x3 matrix which is exactly what it is shown in the image (in red as we have set the R coordinate to 255 and the other two remain at 0).

Filtering collections in C#

If you're using C# 3.0 you can use linq

Or, if you prefer, use the special query syntax provided by the C# 3 compiler:

var filteredList = from x in myList
                   where x > 7
                   select x;

How to set background color of HTML element using css properties in JavaScript

You can use:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>

How can I completely remove TFS Bindings

Old post, so just adding to the answers of @Matt Frear and @Johan Buret. Both work.

But in Matt's case, you also need to set these (VS 2012) in Notepad/text editor:

SccProjectName = ""
SccAuxPath = ""
SccLocalPath = ""
SccProvider = ""

To each project in the solution file (.sln).

@Johan's answer effectively does this....

Apply formula to the entire column

You may fill the column by double-clicking on the bottom right hand corner of the cell which you want to copy from (the point on the box that you would otherwise drag) and it will be applied to whole column.

NB: This doesn't work if you have the filter applied, nor if there is already something already in the cells below.

DataAdapter.Fill(Dataset)

it works for me, just change: Provider=Microsoft.Jet.OLEDB.4.0 (VS2013)

OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\\GENERAL\\OFMPTP_PD_SG.MDB");
DataSet DS = new DataSet();
connection.Open();

string query =
@"SELECT * from MONTHLYPROD";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);

Luis Montoya

How do I "decompile" Java class files?

Soot is an option for newer Java code. At least it has the advantage of still being recently maintained...

Also, Java Decompiler is a decompiler with both a stand-alone GUI and Eclipse integration.

Lastly, Jdec hasn't been mentioned, though it's not as polished as other options.

Change bootstrap datepicker date format on select

this works for me

Open the file bootstrap-datepicker.js

Go to line 1399 and find format: 'mm/dd/yyyy'.

Now you can change the date format here.

Get viewport/window height in ReactJS

Answers by @speckledcarp and @Jamesl are both brilliant. In my case, however, I needed a component whose height could extend the full window height, conditional at render time.... but calling a HOC within render() re-renders the entire subtree. BAAAD.

Plus, I wasn't interested in getting the values as props but simply wanted a parent div that would occupy the entire screen height (or width, or both).

So I wrote a Parent component providing a full height (and/or width) div. Boom.

A use case:

class MyPage extends React.Component {
  render() {
    const { data, ...rest } = this.props

    return data ? (
      // My app uses templates which misbehave badly if you manually mess around with the container height, so leave the height alone here.
      <div>Yay! render a page with some data. </div>
    ) : (
      <FullArea vertical>
        // You're now in a full height div, so containers will vertically justify properly
        <GridContainer justify="center" alignItems="center" style={{ height: "inherit" }}>
          <GridItem xs={12} sm={6}>
            Page loading!
          </GridItem>
        </GridContainer>
      </FullArea>
    )

Here's the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class FullArea extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: 0,
      height: 0,
    }
    this.getStyles = this.getStyles.bind(this)
    this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
  }

  componentDidMount() {
    this.updateWindowDimensions()
    window.addEventListener('resize', this.updateWindowDimensions)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.updateWindowDimensions)
  }

  getStyles(vertical, horizontal) {
    const styles = {}
    if (vertical) {
      styles.height = `${this.state.height}px`
    }
    if (horizontal) {
      styles.width = `${this.state.width}px`
    }
    return styles
  }

  updateWindowDimensions() {
    this.setState({ width: window.innerWidth, height: window.innerHeight })
  }

  render() {
    const { vertical, horizontal } = this.props
    return (
      <div style={this.getStyles(vertical, horizontal)} >
        {this.props.children}
      </div>
    )
  }
}

FullArea.defaultProps = {
  horizontal: false,
  vertical: false,
}

FullArea.propTypes = {
  horizontal: PropTypes.bool,
  vertical: PropTypes.bool,
}

export default FullArea

Scale Image to fill ImageView width and keep aspect ratio

Just use UniversalImageLoader and set

DisplayImageOptions.Builder()
    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
    .build();

and no scale settings on ImageView

How can I get the error message for the mail() function?

If you are on Windows using SMTP, you can use error_get_last() when mail() returns false. Keep in mind this does not work with PHP's native mail() function.

$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
    $errorMessage = error_get_last()['message'];
}

With print_r(error_get_last()), you get something like this:

[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2

How to get index of object by its property in JavaScript?

If you're having issues with IE, you could use the map() function which is supported from 9.0 onward:

var index = Data.map(item => item.name).indexOf("Nick");

python pandas extract year from datetime: df['year'] = df['date'].year is not working

When to use dt accessor

A common source of confusion revolves around when to use .year and when to use .dt.year.

The former is an attribute for pd.DatetimeIndex objects; the latter for pd.Series objects. Consider this dataframe:

df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
                  index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))

The definition of the series and index look similar, but the pd.DataFrame constructor converts them to different types:

type(df.index)     # pandas.tseries.index.DatetimeIndex
type(df['Dates'])  # pandas.core.series.Series

The DatetimeIndex object has a direct year attribute, while the Series object must use the dt accessor. Similarly for month:

df.index.month               # array([1, 1, 1])
df['Dates'].dt.month.values  # array([ 1, 10, 12], dtype=int64)

A subtle but important difference worth noting is that df.index.month gives a NumPy array, while df['Dates'].dt.month gives a Pandas series. Above, we use pd.Series.values to extract the NumPy array representation.

Removing leading zeroes from a field in a SQL statement

you can try this SELECT REPLACE(columnname,'0','') FROM table

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:

$timestampz=time();

function generateRandomString($length = 60) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}


$tokenparta = generateRandomString();


$token = $timestampz*3 . $tokenparta;

echo $token;

Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)

I hope it helps :)

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here it goes.

_x000D_
_x000D_
// Select by value_x000D_
$('select[name="options"]').find('option[value="3"]').attr("selected",true);_x000D_
_x000D_
// Select by text_x000D_
//$('select[name="options"]').find('option:contains("Third")').attr("selected",true);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<body>_x000D_
<select name="options">_x000D_
      <option value="1">First</option>_x000D_
      <option value="2">Second</option>_x000D_
      <option value="3">Third</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

Cross browser compatible JS solution:

_x000D_
_x000D_
var e = document.getElementById('elem');_x000D_
var spin = false;_x000D_
_x000D_
var spinner = function(){_x000D_
e.classList.toggle('running', spin);_x000D_
if (spin) setTimeout(spinner, 2000);_x000D_
}_x000D_
_x000D_
e.onmouseover = function(){_x000D_
spin = true;_x000D_
spinner();_x000D_
};_x000D_
_x000D_
e.onmouseout = function(){_x000D_
spin = false;_x000D_
};
_x000D_
body { _x000D_
height:300px; _x000D_
}_x000D_
#elem {_x000D_
position:absolute;_x000D_
top:20%;_x000D_
left:20%;_x000D_
width:0; _x000D_
height:0;_x000D_
border-style: solid;_x000D_
border-width: 75px;_x000D_
border-color: red blue green orange;_x000D_
border-radius: 75px;_x000D_
}_x000D_
_x000D_
#elem.running {_x000D_
animation: spin 2s linear 0s infinite;_x000D_
}_x000D_
_x000D_
@keyframes spin { _x000D_
100% { transform: rotate(360deg); } _x000D_
}
_x000D_
<div id="elem"></div>
_x000D_
_x000D_
_x000D_

Insert all data of a datagridview to database at once

You can do the same thing with the connection opened just once. Something like this.

for(int i=0; i< dataGridView1.Rows.Count;i++)
  {
    string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";

  try
  {
      SqlConnection conn = new SqlConnection();
      conn.Open();

          using (SqlCommand comm = new SqlCommand(StrQuery, conn))
          {
              comm.ExecuteNonQuery();
          }
      conn.Close();

  }

Also, depending on your specific scenario you may want to look into binding the grid to the database. That would reduce the amount of manual work greatly: http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database

How to merge 2 List<T> and removing duplicate values from it in C#

Union has not good performance : this article describe about compare them with together

var dict = list2.ToDictionary(p => p.Number);
foreach (var person in list1)
{
        dict[person.Number] = person;
}
var merged = dict.Values.ToList();

Lists and LINQ merge: 4820ms
Dictionary merge: 16ms
HashSet and IEqualityComparer: 20ms
LINQ Union and IEqualityComparer: 24ms

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

When is "java.io.IOException:Connection reset by peer" thrown?

It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline

My client was configured to connect to localhost:3000, but no server was running on that port.

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

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

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

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

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

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

How to extract text from a PDF?

The best thing I can currently think of (within the list of "simple" tools) is Ghostscript (current version is v.8.71) and the PostScript utility program ps2ascii.ps. Ghostscript ships it in its lib subdirectory. Try this (on Windows):

gswin32c.exe ^
   -q ^
   -sFONTPATH=c:/windows/fonts ^
   -dNODISPLAY ^
   -dSAFER ^
   -dDELAYBIND ^
   -dWRITESYSTEMDICT ^
   -dCOMPLEX ^
   -f ps2ascii.ps ^
   -dFirstPage=3 ^
   -dLastPage=7 ^
   input.pdf ^
   -dQUIET ^
   -c quit

This command processes pages 3-7 of input.pdf. Read the comments in the ps2ascii.ps file itself to see what the "weird" numbers and additional infos mean (they indicate strings, positions, widths, colors, pictures, rectangles, fonts and page breaks...). To get a "simple" text output, replace the -dCOMPLEX part by -dSIMPLE.

Writing a large resultset to an Excel file using POI

You can using SXSSFWorkbook implementation of Workbook, if you use style in your excel ,You can caching style by Flyweight Pattern to improve your performance. enter image description here

SQL to generate a list of numbers from 1 to 100

SELECT * FROM `DUAL` WHERE id>0 AND id<101

The above query is written in SQL in the database.

How to get these two divs side-by-side?

Using flexbox

   #parent_div_1{
     display:flex;
     flex-wrap: wrap;
  }

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

What's the difference between eval, exec, and compile?

exec is for statement and does not return anything. eval is for expression and returns value of expression.

expression means "something" while statement means "do something".

C# find biggest number

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 3, 9, 5 };
        int biggestNumber = numbers.Max();
        Console.WriteLine(biggestNumber);
        Console.ReadLine();
    }
}

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

Iterate over object keys in node.js

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

javascript regex - look behind alternative?

This is an equivalent solution to Tim Pietzcker's answer (see also comments of same answer):

^(?!.*filename\.js$).*\.js$

It means, match *.js except *filename.js.

To get to this solution, you can check which patterns the negative lookbehind excludes, and then exclude exactly these patterns with a negative lookahead.

Thymeleaf: Concatenation - Could not parse as expression

Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:

th:text="${'static_content - ' + you_variable}"

How to connect to LocalDb

I was able to connect from SSMS using "(LocalDb)\Projects". That's the way it appears in VS2012 as well.

How to make a window always stay on top in .Net?

I had a momentary 5 minute lapse and I forgot to specify the form in full like this:

  myformName.ActiveForm.TopMost = true;

But what I really wanted was THIS!

  this.TopMost = true;

Why I've got no crontab entry on OS X when using vim?

I've never had this problem, but I create a ~/.crontab file and edit that (which allows me to back it up, Time Machine or otherwise), then run

crontab ~/.crontab

Has worked for me for 20+ years across many flavors of unix.

How can I reverse the order of lines in a file?

sort -r < filename

or

rev < filename

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Can't build create-react-app project with custom PUBLIC_URL

Not sure why you aren't able to set it. In the source, PUBLIC_URL takes precedence over homepage

const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

You can try setting breakpoints in their code to see what logic is overriding your environment variable.

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

How to embed images in html email

PHPMailer has the ability to automatically embed images from your HTML email. You have to give full path in the file system, when writing your HTML:

<img src="/var/www/host/images/photo.png" alt="my photo" />

It will automaticaly convert to:

<img src="cid:photo.png" alt="my photo" />

What is the best practice for creating a favicon on a web site?

There are several ways to create a favicon. The best way for you depends on various factors:

  • The time you can spend on this task. For many people, this is "as quick as possible".
  • The efforts you are willing to make. Like, drawing a 16x16 icon by hand for better results.
  • Specific constraints, like supporting a specific browser with odd specs.

First method: Use a favicon generator

If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.

Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.

Second method: Create a favicon.ico (desktop browsers only)

As you suggest, you can create a favicon.ico file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).

Then, declare it in your HTML code:

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">

This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.

About your suggestion of placing the favicon.ico file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).

Third method: Create a favicon.ico, a PNG icon and an Apple Touch icon (all browsers)

In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.

You can achieve a good compatibility with:

  • favicon.ico, see above.
  • A 192x192 PNG icon for Android Chrome
  • A 180x180 Apple Touch icon (for iPhone 6 Plus; other device will scale it down as needed).

Declare them with

<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">

This is not the full story, but it's good enough in most cases.

Unable to start Service Intent

I've found the same problem. I lost almost a day trying to start a service from OnClickListener method - outside the onCreate and after 1 day, I still failed!!!! Very frustrating! I was looking at the sample example RemoteServiceController. Theirs works, but my implementation does not work!

The only way that was working for me, was from inside onCreate method. None of the other variants worked and believe me I've tried them all.

Conclusion:

  • If you put your service class in different package than the mainActivity, I'll get all kind of errors
  • Also the one "/" couldn't find path to the service, tried starting with Intent(package,className) and nothing , also other type of Intent starting

  • I moved the service class in the same package of the activity Final form that works

  • Hopefully this helps someone by defining the listerners onClick inside the onCreate method like this:

    public void onCreate() {
    //some code......
        Button btnStartSrv  = (Button)findViewById(R.id.btnStartService);
        Button btnStopSrv  = (Button)findViewById(R.id.btnStopService);
    
        btnStartSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startService(new Intent("RM_SRV_AIDL"));
            }
        });
    
        btnStopSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent("RM_SRV_AIDL"));
            }
        });
    
    } // end onCreate
    

Also very important for the Manifest file, be sure that service is child of application:

<application ... >
    <activity ... >
     ...
    </activity>
    <service
        android:name="com.mainActivity.MyRemoteGPSService"
        android:label="GPSService"
        android:process=":remote">

        <intent-filter>
             <action android:name="RM_SRV_AIDL" />
        </intent-filter>
    </service>
</application>

How to append new data onto a new line

There is also one fact that you have to consider. You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code

  1. first checks if the file is empty
  2. If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.

Code:

import os

def storescores():
hs = open("hst.txt","a")
if(os.path.getsize("hst.txt") > 0):
   hs.write("\n"+name)
else:
   hs.write(name)

hs.close()

How do I convert a TimeSpan to a formatted string?

By converting it to a datetime, you can get localized formats:

new DateTime(timeSpan.Ticks).ToString("HH:mm");

Creating Dynamic button with click event in JavaScript

this:

element.setAttribute("onclick", alert("blabla"));

should be:

element.onclick = function () {
  alert("blabla");
}

Because you call alert instead push alert as string in attribute

Maintaining href "open in new tab" with an onClick handler in React

You have two options here, you can make it open in a new window/tab with JS:

<td onClick={()=> window.open("someLink", "_blank")}>text</td>

But a better option is to use a regular link but style it as a table cell:

<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>

Resize jqGrid when browser is resized?

If you:

  • have shrinkToFit: false (mean fixed width columns)
  • have autowidth: true
  • don't care about fluid height
  • have horizontal scrollbar

You can make grid with fluid width with following styles:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;
}

.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
   width: auto !important;
}

Here is a demo

How to remove unique key from mysql table

To add a unique key use :

alter table your_table add UNIQUE(target_column_name);

To remove a unique key use:

alter table your_table drop INDEX target_column_name;

Bootstrap 3 grid with no gap

Generalizing on martinedwards and others' ideas, you can glue a bunch of columns together (not just a pair) by adjusting padding of even and odd column children. Adding this definition of a class, .no-gutter, and placing it on your .row element

.row.no-gutter > [class*='col-']:nth-child(2n+1) {
    padding-right: 0;
 } 

.row.no-gutter > [class*='col-']:nth-child(2n) {
    padding-left: 0;
}

Or in SCSS:

.no-gutter  {
    > [class*='col-'] {
        &:nth-child(2n+1) {
            padding-right: 0;
        }
        &:nth-child(2n) {
            padding-left: 0;
        }
    }
}

Move the mouse pointer to a specific position?

You cannot move the mousepointer with javascript.

Just think about the implications for a second, if you could ;)

  1. User thinks: "hey I'd like to click this link"
  2. Javascript moves mousecursor to another link
  3. User clicks wrong link and inadvertently downloads malware that formats his c-drive and eats his candy

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Can refer the code below for the same. Source: Academind/node-restful-api

const express = require('express');
const app = express();

//acts as a middleware
//to handle CORS Errors
app.use((req, res, next) => { //doesn't send response just adjusts it
    res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
    );
    if(req.method === 'OPTIONS'){
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
        return res.status(200).json({});
    }
    next(); //so that other routes can take over
})

How to set text size in a button in html

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

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

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

This way works for me:

1. add your own declaration in a declaration file such as index.d.ts(maybe under the project root)
declare module 'Injector';
2. add your index.d.ts to tsconfig.json
  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }

-- edit: needed quotation marks around module name

filename.whl is not supported wheel on this platform

cp33 means CPython 3.3 you need scipy-0.15.1-cp27-none-win_amd64.whl instead.

Force IE8 Into IE7 Compatiblity Mode

This can be done in IIS: http://weblogs.asp.net/joelvarty/archive/2009/03/23/force-ie7-compatibility-mode-in-ie8-with-iis-settings.aspx

Read the comments as well: Wednesday, April 01, 2009 8:57 AM by John Moore

A quick follow-up. This worked great for my site as long as I use the IE=EmulateIE7 value. Trying to use the IE=7 resulted in my site essentially hanging when run on IE8.

Check if image exists on server using JavaScript?

A better and modern approach is to use ES6 Fetch API to check if an image exists or not:

fetch('https://via.placeholder.com/150', { method: 'HEAD' })
    .then(res => {
        if (res.ok) {
            console.log('Image exists.');
        } else {
            console.log('Image does not exist.');
        }
    }).catch(err => console.log('Error:', err));

Make sure you are either making the same-origin requests or CORS is enabled on the server.

How to merge multiple dicts with same key or different key?

If keys are nested:

d1 = { 'key1': { 'nkey1': 'x1' }, 'key2': { 'nkey2': 'y1' } } 
d2 = { 'key1': { 'nkey1': 'x2' }, 'key2': { 'nkey2': 'y2' } }
ds = [d1, d2]
d = {}
for k in d1.keys():
    for k2 in d1[k].keys():
        d.setdefault(k, {})
        d[k].setdefault(k2, [])
        d[k][k2] = tuple(d[k][k2] for d in ds)

yields:

{'key1': {'nkey1': ('x1', 'x2')}, 'key2': {'nkey2': ('y1', 'y2')}}

Cannot open new Jupyter Notebook [Permission Denied]

On a Windows machine run the python command prompt as administrator. That should resolved the permissions issue when creating a new python 3 notebook.

Multiple Image Upload PHP form with one input

PHP Code

<?php
error_reporting(0);
session_start();
include('config.php');
//define session id
$session_id='1'; 
define ("MAX_SIZE","9000"); 
function getExtension($str)
{
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}

//set the image extentions
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") 
{

    $uploaddir = "uploads/"; //image upload directory
    foreach ($_FILES['photos']['name'] as $name => $value)
    {

        $filename = stripslashes($_FILES['photos']['name'][$name]);
        $size=filesize($_FILES['photos']['tmp_name'][$name]);
        //get the extension of the file in a lower case format
          $ext = getExtension($filename);
          $ext = strtolower($ext);

         if(in_array($ext,$valid_formats))
         {
           if ($size < (MAX_SIZE*1024))
           {
           $image_name=time().$filename;
           echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
           $newname=$uploaddir.$image_name;

           if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) 
           {
           $time=time();
               //insert in database
           mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
            }

           }
           else
           {
            echo '<span class="imgList">You have exceeded the size limit!</span>';

           }

          }
          else
         { 
             echo '<span class="imgList">Unknown extension!</span>';

         }

     }
}

?>

Jquery Code

<script>
 $(document).ready(function() { 

            $('#photoimg').die('click').live('change', function()            { 

                $("#imageform").ajaxForm({target: '#preview', 
                     beforeSubmit:function(){ 

                    console.log('ttest');
                    $("#imageloadstatus").show();
                     $("#imageloadbutton").hide();
                     }, 
                    success:function(){ 
                    console.log('test');
                     $("#imageloadstatus").hide();
                     $("#imageloadbutton").show();
                    }, 
                    error:function(){ 
                    console.log('xtest');
                     $("#imageloadstatus").hide();
                    $("#imageloadbutton").show();
                    } }).submit();


            });
        }); 
</script>

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

One way is to simply destroy the listener once you are done with it.

var removeListener = $scope.$on('navBarRight-ready', function () {
        $rootScope.$broadcast('workerProfile-display', $scope.worker)
        removeListener(); //destroy the listener
    })

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

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

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

How to find the Vagrant IP?

I did at VagrantFile:

REMOTE_IP = %x{/usr/local/bin/vagrant ssh-config | /bin/grep -i HostName | /usr/bin/cut -d\' \' -f4}
run "ping #{REMOTE_IP}"

As you can see, I used the "%x{}" ruby function.

Plot multiple lines (data series) each with unique color in R

If your data is in wide format matplot is made for this and often forgotten about:

 dat <- matrix(runif(40,1,20),ncol=4) # make data
 matplot(dat, type = c("b"),pch=1,col = 1:4) #plot
 legend("topleft", legend = 1:4, col=1:4, pch=1) # optional legend

There is also the added bonus for those unfamiliar with things like ggplot that most of the plotting paramters such as pch etc. are the same using matplot() as plot(). enter image description here

push multiple elements to array

If you want to add multiple items, you have to use the spread operator

a = [1,2]
b = [3,4,5,6]
a.push(...b)

The output will be

a = [1,2,3,4,5,6]

Accessing localhost (xampp) from another computer over LAN network - how to?

Localhost is just a name given for the loopback, eg its like referring to yourself as "me" ..

To view it from other computers, chances are you need only do http://192.168.1.56 or http://myPcsName if that doesnt work, there is a chance that there is a firewall running on your computer, or the httpd.conf is only listening on 127.0.0.1

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

jQuery ajax post file field

Try this...

<script type="text/javascript">
      $("#form_oferta").submit(function(event) 
      {
           var myData = $( form ).serialize(); 
           $.ajax({
                type: "POST", 
                contentType:attr( "enctype", "multipart/form-data" ),
                url: " URL Goes Here ",  
                data: myData,  
                success: function( data )  
                {
                     alert( data );
                }
           });
           return false;  
      });
</script>

Here the contentType is specified as multipart/form-data as we do in the form tag, this will work to upload simple file On server side you just need to write simple file upload code to handle this request with echoing message you want to show to user as a response.

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid on the parent, grid-area: 1/1/1/1; on the children, and justify-self for positioning of those children.

_x000D_
_x000D_
<div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
  <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Are PHP Variables passed by value or by reference?

Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.

function add(&$var){ // The &amp; is before the argument $var
   $var++;
}
$a = 1;
$b = 10;
add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; // Note: $a and $b are NOT referenced

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Getting "Cannot call a class as a function" in my React Project

Hi in my case solutions here won't work My code:

index.js

import App from './App';

let store = createStore(App);

render(
    <Provider store={store}>
        <Router history={browserHistory}>
            <Route path="/" name='Strona glówna' component={App}>
                <IndexRoute name='' component={Welcome}/>
                <Route name='Dashboard' path="dashboard" component={ReatEstateList}/>

Error apeares in App.js after import

Uncaught TypeError: Cannot call a class as a function

Python list / sublist selection -1 weirdness

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Is there a way to detach matplotlib plots so that the computation can continue?

You may want to read this document in matplotlib's documentation, titled:

Using matplotlib in a python shell

Bootstrap carousel width and height

I know this is an older post but Bootstrap is still alive and kicking!

Slightly different to @Eduardo's post, I had to modify:

#myCarousel.carousel.slide {
    width: 100%; 
    max-width: 400px; !important
}

When I only modified .carousel-inner {}, the actual image was fixed size but the left/right controls were displaying incorrectly off to the side of the div.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.

I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.

How can I insert new line/carriage returns into an element.textContent?

I found that inserting \\n works. I.e., you escape the escaped new line character

Convert Unix timestamp to a date string

Python:

python -c "from datetime import datetime; print(datetime.fromtimestamp($TIMESTAMP))"

How to convert POJO to JSON and vice versa?

You can use jackson api for the conversion

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.4</version>
</dependency>

add above maven dependency in your POM, In your main method create ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

later we nee to add our POJO class to the mapper

String json = mapper.writeValueAsString(pojo);

Convert a tensor to numpy array in Tensorflow?

Any tensor returned by Session.run or eval is a NumPy array.

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

Or:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

Or, equivalently:

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

EDIT: Not any tensor returned by Session.run or eval() is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

Disabling Chrome cache for website development

Chrome's Cache killer is by far the best option. Since the store URL to install cache killer is down, you can download the CRX file here:

https://www.crx4chrome.com/extensions/jpfbieopdmepaolggioebjmedmclkbap/

once the extension file is downloaded, open Chrome -> more tools -> extensions, then drag the CRX file from the File Explorer or your Desktop (depending the location where you downloaded the file) into the chrome window to install the extension.

Git workflow and rebase vs merge questions

"Even if you’re a single developer with only a few branches, it’s worth it to get in the habit of using rebase and merge properly. The basic work pattern will look like:

  • Create new branch B from existing branch A

  • Add/commit changes on branch B

  • Rebase updates from branch A

  • Merge changes from branch B onto branch A"

https://www.atlassian.com/git/tutorials/merging-vs-rebasing/

Get size of all tables in database

This will give you the sizes, and record counts for each table.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- Get a list of tables and their sizes on disk
ALTER PROCEDURE [dbo].[sp_Table_Sizes]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
DECLARE @table_name VARCHAR(500)  
DECLARE @schema_name VARCHAR(500)  
DECLARE @tab1 TABLE( 
        tablename VARCHAR (500) collate database_default 
       ,schemaname VARCHAR(500) collate database_default 
) 

CREATE TABLE #temp_Table ( 
        tablename sysname 
       ,row_count INT 
       ,reserved VARCHAR(50) collate database_default 
       ,data VARCHAR(50) collate database_default 
       ,index_size VARCHAR(50) collate database_default 
       ,unused VARCHAR(50) collate database_default  
) 

INSERT INTO @tab1  
SELECT Table_Name, Table_Schema  
FROM information_schema.tables  
WHERE TABLE_TYPE = 'BASE TABLE' 

DECLARE c1 CURSOR FOR 
SELECT Table_Schema + '.' + Table_Name   
FROM information_schema.tables t1  
WHERE TABLE_TYPE = 'BASE TABLE' 

OPEN c1 
FETCH NEXT FROM c1 INTO @table_name 
WHILE @@FETCH_STATUS = 0  
BEGIN   
        SET @table_name = REPLACE(@table_name, '[','');  
        SET @table_name = REPLACE(@table_name, ']','');  

        -- make sure the object exists before calling sp_spacedused 
        IF EXISTS(SELECT id FROM sysobjects WHERE id = OBJECT_ID(@table_name)) 
        BEGIN 
               INSERT INTO #temp_Table EXEC sp_spaceused @table_name, false; 
        END 

        FETCH NEXT FROM c1 INTO @table_name 
END 
CLOSE c1 
DEALLOCATE c1 

SELECT  t1.* 
       ,t2.schemaname  
FROM #temp_Table t1  
INNER JOIN @tab1 t2 ON (t1.tablename = t2.tablename ) 
ORDER BY schemaname,t1.tablename; 

DROP TABLE #temp_Table
END

Display string as html in asp.net mvc view

You should be using IHtmlString instead:

IHtmlString str = new HtmlString("<a href="/Home/Profile/seeker">seeker</a> has applied to <a href="/Jobs/Details/9">Job</a> floated by you.</br>");

Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:

@Html.Raw(str)

Compared to:

@str

Also, I also think it's a bit safer vs. using @Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).

I generally try to avoid using Html.Raw() whenever possible.

One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.

First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.

Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like @Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I just used -static-libstdc++ while building. w/ that, I can run the a.out

g++ test.cpp -static-libstdc++

How can I make sticky headers in RecyclerView? (Without external lib)

you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:

  • can interact with the sticy header (tap/long press/swipe)
  • the sticky header hides and reveals itself properly...even if each view holder has a different height (some other answers here don't handle that properly, causing the wrong headers to show, or the headers to jump up and down)

see an example of the 2 files being used in this small github project i whipped up

How to get page content using cURL?

Get content with Curl php

request server support Curl function, enable in httpd.conf in folder Apache


function UrlOpener($url)
     global $output;
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $output = curl_exec($ch); 
     curl_close($ch);    
     echo $output;

If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/

If a folder does not exist, create it

Use this code if the folder is not presented under the image folder or other folders

string subPath = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/");

bool exists = System.IO.Directory.Exists(subPath);
if(!exists)
    System.IO.Directory.CreateDirectory(subPath);

string path = HttpContext.Current.Server.MapPath(@"~/Images/RequisitionBarCode/" + OrderId + ".png");

git rm - fatal: pathspec did not match any files

This chains work in my case:

  1. git rm -r WebApplication/packages

There was a confirmation git-dialog. You should choose "y" option.

  1. git commit -m "blabla"
  2. git push -f origin <ur_branch>

How do I access ViewBag from JS

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
 <script>
   var AppConfig = @Html.Raw(Json.Encode(new {
    baseUrl: Url.Content("~"),
    fbApi: "get it from db",
    awsUrl: "get it from db"
   }));
 </script>
</head>

And you can use it in your JavaScript code as follow:

<script>
  myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
  alert(myProduct.fullUrl);
</script>

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

How do I create a URL shortener?

Don't know if anyone will find this useful - it is more of a 'hack n slash' method, yet is simple and works nicely if you want only specific chars.

$dictionary = "abcdfghjklmnpqrstvwxyz23456789";
$dictionary = str_split($dictionary);

// Encode
$str_id = '';
$base = count($dictionary);

while($id > 0) {
    $rem = $id % $base;
    $id = ($id - $rem) / $base;
    $str_id .= $dictionary[$rem];
}


// Decode
$id_ar = str_split($str_id);
$id = 0;

for($i = count($id_ar); $i > 0; $i--) {
    $id += array_search($id_ar[$i-1], $dictionary) * pow($base, $i - 1);
} 

How to install a plugin in Jenkins manually

I have created a simple script that does the following:

  • Download one or more plugins to the plugin directory
  • Scan all plugins in that directory for missing dependencies
  • download this dependencies as well
  • loop until no open dependencies are left

The script requires no running jenkins - I use it to provision a docker box.

https://gist.github.com/micw/e80d739c6099078ce0f3

How to connect to LocalDB in Visual Studio Server Explorer?

It worked for me.

  1. Open command prompt
  2. Run "SqlLocalDB.exe start"
  3. System response "LocalDB instance "mssqllocaldb" started."
  4. In VS, View/Server Explorer/(Right click) Data Connections/Add Connection
    • Data Source: Microsoft SQL Server (SqlClient)
    • Server name: (localdb)\MSSQLLocalDB
    • Log on to the server: Use Windows Authentication
  5. Press "Test Connection", Then OK.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

python object() takes no parameters error

You've mixed tabs and spaces. __init__ is actually defined nested inside another method, so your class doesn't have its own __init__ method, and it inherits object.__init__ instead. Open your code in Notepad instead of whatever editor you're using, and you'll see your code as Python's tab-handling rules see it.

This is why you should never mix tabs and spaces. Stick to one or the other. Spaces are recommended.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

How to efficiently build a tree from a flat structure?

Vague as the question seems to me, I would probably create a map from the ID to the actual object. In pseudo-java (I didn't check whether it works/compiles), it might be something like:

Map<ID, FlatObject> flatObjectMap = new HashMap<ID, FlatObject>();

for (FlatObject object: flatStructure) {
    flatObjectMap.put(object.ID, object);
}

And to look up each parent:

private FlatObject getParent(FlatObject object) {
    getRealObject(object.ParentID);
}

private FlatObject getRealObject(ID objectID) {
    flatObjectMap.get(objectID);
}

By reusing getRealObject(ID) and doing a map from object to a collection of objects (or their IDs), you get a parent->children map too.

How to display a Windows Form in full screen on top of the taskbar?

I believe that it can be done by simply setting your FormBorderStyle Property to None and the WindowState to Maximized. If you are using Visual Studio both of those can be found in the IDE so there is no need to do so programmatically. Make sure to include some way of closing/exiting the program before doing this cause this will remove that oh so helpful X in the upper right corner.

EDIT:

Try this instead. It is a snippet that I have kept for a long time. I can't even remember who to credit for it, but it works.

/*
 * A function to put a System.Windows.Forms.Form in fullscreen mode
 * Author: Danny Battison
 * Contact: [email protected]
 */

        // a struct containing important information about the state to restore to
        struct clientRect
        {
            public Point location;
            public int width;
            public int height;
        };
        // this should be in the scope your class
        clientRect restore;
                bool fullscreen = false;

        /// <summary>
        /// Makes the form either fullscreen, or restores it to it's original size/location
        /// </summary>
        void Fullscreen()
        {
            if (fullscreen == false)
            {
                this.restore.location = this.Location;
                this.restore.width = this.Width;
                this.restore.height = this.Height;
                this.TopMost = true;
                this.Location = new Point(0,0);
                this.FormBorderStyle = FormBorderStyle.None;
                this.Width = Screen.PrimaryScreen.Bounds.Width;
                this.Height = Screen.PrimaryScreen.Bounds.Height;
            }
            else
            {
                this.TopMost = false;
                this.Location = this.restore.location;
                this.Width = this.restore.width;
                this.Height = this.restore.height;
                                // these are the two variables you may wish to change, depending
                                // on the design of your form (WindowState and FormBorderStyle)
                this.WindowState = FormWindowState.Normal;
                this.FormBorderStyle = FormBorderStyle.Sizable;
            }
        }

Importing lodash into angular2 + typescript application

Partial import from lodash should work in angular 4.1.x using following notation:

let assign = require('lodash/assign');

Or use 'lodash-es' and import in module:

import { assign } from 'lodash-es';

What's the difference between ASCII and Unicode?

Storage

Given numbers are only for storing 1 character

  • ASCII ? 27 bits (1 byte)
  • Extended ASCII ? 28 bits (1 byte)
  • UTF-8 ? minimum 28, maximum 232 bits (min 1, max 4 bytes)
  • UTF-16 ? minimum 216, maximum 232 bits (min 2, max 4 bytes)
  • UTF-32 ? 232 bits (4 bytes)

Usage (as of Feb 2020)

Percentages of websites using various character encodings

Android: Create spinner programmatically from array

In Kotlin language you can do it in this way:

val values = arrayOf(
    "cat",
    "dog",
    "chicken"
)

ArrayAdapter(
    this,
    android.R.layout.simple_spinner_item,
    values
).also {
    it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinner.adapter = it
}

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

When I catch an exception, how do I get the type, file, and line number?

Here is an example of showing the line number of where exception takes place.

import sys
try:
    print(5/0)
except Exception as e:
    print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)

print('And the rest of program continues')

Why use $_SERVER['PHP_SELF'] instead of ""

In addition to above answers, another way of doing it is $_SERVER['PHP_SELF'] or simply using an empty string is to use __DIR__.
OR
If you're on a lower PHP version (<5.3), a more common alternative is to use dirname(__FILE__)
Both returns the folder name of the file in context.

EDIT
As Boann pointed out that this returns the on-disk location of the file. WHich you would not ideally expose as a url. In that case dirname($_SERVER['PHP_SELF']) can return the folder name of the file in context.