Programs & Examples On #Deb

deb is the extension of the Debian binary package format. Software packaged for Debian or Debian derivatives such as Ubuntu is distributed in this format.

Install sbt on ubuntu

As an alternative approach, you can save the SBT Extras script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.

The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.

Get the current year in JavaScript

Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:

let currentYear = new Date().getFullYear;

The currentYear variable will hold the value you are looking out for.

How do I mock a REST template exchange?

The RestTemplate instance has to be a real object. It should work if you create a real instance of RestTemplate and make it @Spy.

@Spy
private RestTemplate restTemplate = new RestTemplate();

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

Get epoch for a specific date using Javascript

Take a look at http://www.w3schools.com/jsref/jsref_obj_date.asp

There is a function UTC() that returns the milliseconds from the unix epoch.

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

How to set a Default Route (To an Area) in MVC

Thanks to Aaron for pointing out that it's about locating the views, I misunderstood that.

[UPDATE] I just created a project that sends the user to an Area per default without messing with any of the code or lookup paths:

In global.asax, register as usual:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = ""}  // Parameter defaults,
        );
    }

in Application_Start(), make sure to use the following order;

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }

in you area registration, use

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "ShopArea_default",
            "{controller}/{action}/{id}",
            new { action = "Index", id = "", controller = "MyRoute" },
            new { controller = "MyRoute" }
        );
    }

An example can be found at http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/

I really hope that this is what you were asking for...

////

I don't think that writing a pseudo ViewEngine is the best solution in this case. (Lacking reputation, I can't comment). The WebFormsViewEngine is Area aware and contains AreaViewLocationFormats which is defined per default as

AreaViewLocationFormats = new[] {
        "~/Areas/{2}/Views/{1}/{0}.aspx",
        "~/Areas/{2}/Views/{1}/{0}.ascx",
        "~/Areas/{2}/Views/Shared/{0}.aspx",
        "~/Areas/{2}/Views/Shared/{0}.ascx",
    };

I believe you don't adhere to this convention. You posted

public ActionResult ActionY() 
{ 
    return View("~/Areas/AreaZ/views/ActionY.aspx"); 
} 

as a working hack, but that should be

   return View("~/Areas/AreaZ/views/ControllerX/ActionY.aspx"); 

IF you don't want to follow the convention, however, you might want to take a short path by either deriving from the WebFormViewEngine (that is done in MvcContrib, for example) where you can set the lookup paths in the constructor, or -a little hacky- by specifying your convention like this on Application_Start:

((VirtualPathProviderViewEngine)ViewEngines.Engines[0]).AreaViewLocationFormats = ...;

This should be performed with a little more care, of course, but I think it shows the idea. These fields are public in VirtualPathProviderViewEngine in MVC 2 RC.

Mercurial: how to amend the last commit?

With the release of Mercurial 2.2, you can use the --amend option with hg commit to update the last commit with the current working directory

From the command line reference:

The --amend flag can be used to amend the parent of the working directory with a new commit that contains the changes in the parent in addition to those currently reported by hg status, if there are any. The old commit is stored in a backup bundle in .hg/strip-backup (see hg help bundle and hg help unbundle on how to restore it).

Message, user and date are taken from the amended commit unless specified. When a message isn't specified on the command line, the editor will open with the message of the amended commit.

The great thing is that this mechanism is "safe", because it relies on the relatively new "Phases" feature to prevent updates that would change history that's already been made available outside of the local repository.

jQuery animate margin top

use 'marginTop' instead of MarginTop

$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);

MAMP mysql server won't start. No mysql processes are running

If you are using MAMP PRO 5.7+ (18029)

1.Just stop MAMPRO. 2.Goto to directory /Applications/MAMP/db/mysql## (Where ## is the Number of your Mysql version) 3.List the files with command: ls -l * 4. Type command: rm ib_logfile* #Just must delete theses 2 files. 5.Restart MAMPRO and its must works fine!

Caution: If you remove the files ibdata1 will destroy all you "databases"

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

How to remove an element slowly with jQuery?

All the answers are good, but I found they all lacked that professional "polish".

I came up with this, fading out, sliding up, then removing:

$target.fadeTo(1000, 0.01, function(){ 
    $(this).slideUp(150, function() {
        $(this).remove(); 
    }); 
});

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to automatically crop and center an image

Try this:

#yourElementId
{
    background: url(yourImageLocation.jpg) no-repeat center center;
    width: 100px;
    height: 100px;
}

Keep in mind that width and height will only work if your DOM element has layout (a block displayed element, like a div or an img). If it is not (a span, for example), add display: block; to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

php form action php self

Another (and in my opinion proper) method is use the __FILE__ constant if you don't like to rely on $_SERVER variables.

$parts = explode(DIRECTORY_SEPARATOR, __FILE__);
$fileName = end($parts);
echo $fileName;

About magic and predefined constants: 1, 2.

Byte array to image conversion

there is a simple approach as below, you can use FromStream method of an image to do the trick, Just remember to use System.Drawing;

// using image object not file 
public byte[] imageToByteArray(Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

The property 'Id' is part of the object's key information and cannot be modified

The entity that was created by the framework doesn't have a contact.ContactTypeId property. It automatically removed it and created the ContactType association inside the Contact entity.

The way to get it to work, as you suggested, is to create a ContactType object by querying the database and assigning it to contact.ContactType. For example:

Contact contact = dbContext.Contacts.Single(c => c.Id == 12345);
ContactType contactType = dbContext.ContactType.Single(c => c.Id == 3);
contact.ContactType = contactType;

Undefined reference to vtable

I just ran into another cause for this error that you can check for.

The base class defined a pure virtual function as:

virtual int foo(int x = 0);

And the subclass had

int foo(int x) override;

The problem was the typo that the "=0" was supposed to be outside of the parenthesis:

virtual int foo(int x) = 0;

So, in case you're scrolling this far down, you probably didn't find the answer - this is something else to check for.

Base64 encoding in SQL Server 2005 T-SQL

You can use just:

Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)

then after encoding you'll receive text 'MjE4Nqk5'

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

When to use .First and when to use .FirstOrDefault with LINQ?

someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)

Which one to use? It should be decided by the business logic, and not the fear of exception/programm failure.

For instance, If business logic says that we can not have zero transactions on any working day (Just assume). Then you should not try to handle this scenario with some smart programming. I will always use First() over such collection, and let the program fail if something else screwed up the business logic.

Code:

var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()

I would like to see others comments over this.

Visual Studio 2008 Product Key in Registry?

Just delete key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

Or run in command line:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

Trigger 404 in Spring-MVC controller?

Simply you can use web.xml to add error code and 404 error page. But make sure 404 error page must not locate under WEB-INF.

<error-page>
    <error-code>404</error-code>
    <location>/404.html</location>
</error-page>

This is the simplest way to do it but this have some limitation. Suppose if you want to add the same style for this page that you added other pages. In this way you can't to that. You have to use the @ResponseStatus(value = HttpStatus.NOT_FOUND)

Check existence of input argument in a Bash shell script

As a small reminder, the numeric test operators in Bash only work on integers (-eq, -lt, -ge, etc.)

I like to ensure my $vars are ints by

var=$(( var + 0 ))

before I test them, just to defend against the "[: integer arg required" error.

React Native version mismatch

In my case installing a new virtual device helped. Now I am using 1 device per app.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

How to pass data from child component to its parent in ReactJS?

This should work. While sending the prop back you are sending that as an object rather send that as a value or alternatively use it as an object in the parent component. Secondly you need to format your json object to contain name value pairs and use valueField and textField attribute of DropdownList

Short Answer

Parent:

<div className="col-sm-9">
     <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
</div>

Child:

handleLangChange = () => {
    var lang = this.dropdown.value;
    this.props.onSelectLanguage(lang);            
}

Detailed:

EDIT:

Considering React.createClass is deprecated from v16.0 onwards, It is better to go ahead and create a React Component by extending React.Component. Passing data from child to parent component with this syntax will look like

Parent

class ParentComponent extends React.Component {

    state = { language: '' }

    handleLanguage = (langValue) => {
        this.setState({language: langValue});
    }

    render() {
         return (
                <div className="col-sm-9">
                    <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
                </div>
        )
     }
}

Child

var json = require("json!../languages.json");
var jsonArray = json.languages;

export class SelectLanguage extends React.Component {
    state = {
            selectedCode: '',
            selectedLanguage: jsonArray[0],
        }

    handleLangChange = () => {
        var lang = this.dropdown.value;
        this.props.onSelectLanguage(lang);            
    }

    render() {
        return (
            <div>
                <DropdownList ref={(ref) => this.dropdown = ref}
                    data={jsonArray} 
                    valueField='lang' textField='lang'
                    caseSensitive={false} 
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />
            </div>            
        );
    }
}

Using createClass syntax which the OP used in his answer Parent

const ParentComponent = React.createClass({
    getInitialState() {
        return {
            language: '',
        };
    },

    handleLanguage: function(langValue) {
        this.setState({language: langValue});
    },

    render() {
         return (
                <div className="col-sm-9">
                    <SelectLanguage onSelectLanguage={this.handleLanguage} /> 
                </div>
        );
});

Child

var json = require("json!../languages.json");
var jsonArray = json.languages;

export const SelectLanguage = React.createClass({
    getInitialState: function() {
        return {
            selectedCode: '',
            selectedLanguage: jsonArray[0],
        };
    },

    handleLangChange: function () {
        var lang = this.refs.dropdown.value;
        this.props.onSelectLanguage(lang);            
    },

    render() {

        return (
            <div>
                <DropdownList ref='dropdown'
                    data={jsonArray} 
                    valueField='lang' textField='lang'
                    caseSensitive={false} 
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />
            </div>            
        );
    }
});

JSON:

{ 
"languages":[ 

    { 
    "code": "aaa", 
    "lang": "english" 
    }, 
    { 
    "code": "aab", 
    "lang": "Swedish" 
    }, 
  ] 
}

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

Bootstrap row class contains margin-left and margin-right which creates problems

To remove the margins on all rows:

.row {
    margin: 0px !important;
}

How to make a parent div auto size to the width of its children divs

Your interior <div> elements should likely both be float:left. Divs size to 100% the size of their container width automatically. Try using display:inline-block instead of width:auto on the container div. Or possibly float:left the container and also apply overflow:auto. Depends on what you're after exactly.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

i had the same problem and besides the above posts' configurations putting

            <plugin>
            <groupId>com.google.appengine</groupId>
            <artifactId>appengine-maven-plugin</artifactId>
            <version>1.9.32</version>
            <configuration>
                <enableJarClasses>false</enableJarClasses>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>endpoints_get_discovery_doc</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

in the plugins element in pom.xml. i think the problem was absence of execution -> goal "endpoints_get_discovery_doc" in some cases like mine, so this worked for me.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

MySQL: Grant **all** privileges on database

Hello I used this code to have the super user in mysql

GRANT EXECUTE, PROCESS, SELECT, SHOW DATABASES, SHOW VIEW, ALTER, ALTER ROUTINE,
    CREATE, CREATE ROUTINE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,
    EVENT, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE, CREATE USER, FILE,
    LOCK TABLES, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHUTDOWN,
    SUPER
        ON *.* TO mysql@'%'
    WITH GRANT OPTION;

and then

FLUSH PRIVILEGES;

How to save a new sheet in an existing excel file, using Pandas?

You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.

import pandas as pd
import numpy as np

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>

# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()

If you want to preserve all existing sheets, you can replace above code between begin and end with:

# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
    df = xlsx.parse(sheet_name=sheet, index_col=0)
    df.to_excel(writer, sheet_name=sheet)

What causes javac to issue the "uses unchecked or unsafe operations" warning

You can keep it in the generic form and write it as:

// list 2 is made generic and can store any type of Object
        ArrayList<Object> list2 = new ArrayList<Object>();

Setting type of ArrayList as Object gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.

Error: could not find function ... in R

You may be able to fix this error by name spacing :: the function call

comparison.cloud(colors = c("red", "green"), max.words = 100)

to

wordcloud::comparison.cloud(colors = c("red", "green"), max.words = 100)

How do you change the text in the Titlebar in Windows Forms?

public partial class Form1 : Form
{
    DateTime date = new DateTime();
    public Form1()
    {
        InitializeComponent();
}
    private void timer1_Tick(object sender, EventArgs e)
    {
        date = DateTime.Now;
        this.Text = "Date: "+date;
    }
}

I was having some problems with inserting date and time into the name of the form. Finally found the error. I'm posting this in case anyone has the same problem and doesn't have to spend years googling solutions.

cast class into another class or convert class to another

By using following code you can copy any class object to another class object for same name and same type of properties.

public class CopyClass
{
    /// <summary>
    /// Copy an object to destination object, only matching fields will be copied
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sourceObject">An object with matching fields of the destination object</param>
    /// <param name="destObject">Destination object, must already be created</param>
    public static void CopyObject<T>(object sourceObject, ref T destObject)
    {
        //  If either the source, or destination is null, return
        if (sourceObject == null || destObject == null)
            return;

        //  Get the type of each object
        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        //  Loop through the source properties
        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            //  Get the matching property in the destination object
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            //  If there is none, skip
            if (targetObj == null)
                continue;

            //  Set the value in the destination
            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
    }
}

Call Method Like,

ClassA objA = new ClassA();
ClassB objB = new ClassB();

CopyClass.CopyObject(objOfferMast, ref objB);

It will copy objA into objB.

Copy folder recursively, excluding some folders

Similar to Jeff's idea (untested):

find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

how to add picasso library in android studio

Dependency

dependencies {

   implementation 'com.squareup.picasso:picasso:2.71828'

}

//Java Code for Image Loading into imageView

Picasso.get().load(werURL).into(imageView);

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Proper use of 'yield return'

The two pieces of code are really doing two different things. The first version will pull members as you need them. The second version will load all the results into memory before you start to do anything with it.

There's no right or wrong answer to this one. Which one is preferable just depends on the situation. For example, if there's a limit of time that you have to complete your query and you need to do something semi-complicated with the results, the second version could be preferable. But beware large resultsets, especially if you're running this code in 32-bit mode. I've been bitten by OutOfMemory exceptions several times when doing this method.

The key thing to keep in mind is this though: the differences are in efficiency. Thus, you should probably go with whichever one makes your code simpler and change it only after profiling.

Password Strength Meter

Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/

I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?

How can I break up this long line in Python?

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator (+):

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

How to Convert double to int in C?

int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);

this code gives the output as b=3669 only you check it clearly.

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

How can I pass a reference to a function, with parameters?

You can also overload the Function prototype:

// partially applies the specified arguments to a function, returning a new function
Function.prototype.curry = function( ) {
    var func = this;
    var slice = Array.prototype.slice;
    var appliedArgs = slice.call( arguments, 0 );

    return function( ) {
        var leftoverArgs = slice.call( arguments, 0 );
        return func.apply( this, appliedArgs.concat( leftoverArgs ) );
    };
};

// can do other fancy things:

// flips the first two arguments of a function
Function.prototype.flip = function( ) {
    var func = this;
    return function( ) {
        var first = arguments[0];
        var second = arguments[1];
        var rest = Array.prototype.slice.call( arguments, 2 );
        var newArgs = [second, first].concat( rest );

        return func.apply( this, newArgs );
    };
};

/*
e.g.

var foo = function( a, b, c, d ) { console.log( a, b, c, d ); }
var iAmA = foo.curry( "I", "am", "a" );
iAmA( "Donkey" );
-> I am a Donkey

var bah = foo.flip( );
bah( 1, 2, 3, 4 );
-> 2 1 3 4
*/

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Access index of the parent ng-repeat from child ng-repeat

According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

so you can write

<div ng-repeat="(fIndex, f) in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething(fIndex)">Add Something</a>
    </div>
  </div>
</div>

One level up is still quite clean with $parent.$index but several parents up, things can get messy.

Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

iOS: set font size of UILabel Programmatically

Objective-C:

[label setFont: [label.font fontWithSize: sizeYouWant]];

Swift:

label.font = label.font.fontWithSize(sizeYouWant)

just changes font size of a UILabel.

Using Javascript in CSS

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.

HTC with IE

Use a CSS rule like so:

body {
  behavior:url(script.htc);
}

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

XBL with Firefox

Firefox supports a similar XML-script-executing hack, using XBL.

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>

All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

How do you migrate an IIS 7 site to another server?

MSDeploy can migrate all content, config, etc. that is what the IIS team recommends. http://www.iis.net/extensions/WebDeploymentTool

To create a package, run the following command (replace Default Web Site with your web site name):

msdeploy.exe -verb:sync -source:apphostconfig="Default Web Site" -dest:package=c:\dws.zip > DWSpackage7.log

To restore the package, run the following command:

msdeploy.exe -verb:sync -source:package=c:\dws.zip -dest:apphostconfig="Default Web Site" > DWSpackage7.log

How can I see an the output of my C programs using Dev-C++?

; It works...

#include <iostream>
using namespace std;
int main ()
{
   int x,y; // (Or whatever variable you want you can)

your required process syntax type here then;

   cout << result 

(or your required output result statement); use without space in getchar and other syntax.

   getchar();
}

Now you can save your file with .cpp extension and use ctrl + f 9 to compile and then use ctrl + f 10 to execute the program. It will show you the output window and it will not vanish with a second Until you click enter to close the output window.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

Splitting a list into N parts of approximately equal length

This will do the split by a single expression:

>>> myList = range(18)
>>> parts = 5
>>> [myList[(i*len(myList))//parts:((i+1)*len(myList))//parts] for i in range(parts)]
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17]]

The list in this example has the size 18 and is divided into 5 parts. The size of the parts differs in no more than one element.

How to select specific columns in laravel eloquent

By using all() method we can select particular columns from table like as shown below.

ModelName::all('column1', 'column2', 'column3');

Note: Laravel 5.4

Reliable and fast FFT in Java

I guess it depends on what you are processing. If you are calculating the FFT over a large duration you might find that it does take a while depending on how many frequency points you are wanting. However, in most cases for audio it is considered non-stationary (that is the signals mean and variance changes to much over time), so taking one large FFT (Periodogram PSD estimate) is not an accurate representation. Alternatively you could use Short-time Fourier transform, whereby you break the signal up into smaller frames and calculate the FFT. The frame size varies depending on how quickly the statistics change, for speech it is usually 20-40ms, for music I assume it is slightly higher.

This method is good if you are sampling from the microphone, because it allows you to buffer each frame at a time, calculate the fft and give what the user feels is "real time" interaction. Because 20ms is quick, because we can't really perceive a time difference that small.

I developed a small bench mark to test the difference between FFTW and KissFFT c-libraries on a speech signal. Yes FFTW is highly optimised, but when you are taking only short-frames, updating the data for the user, and using only a small fft size, they are both very similar. Here is an example on how to implement the KissFFT libraries in Android using LibGdx by badlogic games. I implemented this library using overlapping frames in an Android App I developed a few months ago called Speech Enhancement for Android.

Are there any Java method ordering conventions?

40 methods in a single class is a bit much.

Would it make sense to move some of the functionality into other - suitably named - classes. Then it is much easier to make sense of.

When you have fewer, it is much easier to list them in a natural reading order. A frequent paradigm is to list things either before or after you need them , in the order you need them.

This usually means that main() goes on top or on bottom.

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.

I also did som further research with a test form and found that when the the current culture was set to "no" or "nb-NO" at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!

I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.

Better way to revert to a previous SVN revision of a file?

Reverse merge is exactly what you want (see luapyad's answer). Just apply the merge to the erroneously-commited file instead of the entire directory.

How to convert Set to Array?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

Indeed, there are several ways to convert a Set to an Array:

using Array.from

let array = Array.from(mySet);

Simply spreading the Set out in an array

let array = [...mySet];

The old fashion way, iterating and pushing to a new array (Sets do have forEach)

let array = [];
mySet.forEach(v => array.push(v));

Previously, using the non-standard, and now deprecated array comprehension syntax:

let array = [v for (v of mySet)];

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I had this same issue. I was working with a team of developers using a Mac and everybody else on the team was running Windows. However we were using the Anroid Studio 2.2-beta with jdk 1.8. If you are on a mac and come across this issue, here is how to solve it. DONT USE Android Studio 2.2-beta. I spent hours trying to debug this error in 2.2-beta. I solved it by simply changing to Android Studio 2.1.3. Our app ran instantly after changing the Android Studio version. Also on Android Studio's website before you download it warns mac users about running jdk 1.8 on 2.2 beta. Guess I should have read the fine print haha

How do I rotate the Android emulator display?

Press Ctrl + F10 to rotate the emulator screen.

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

Get combobox value in Java swing

Method Object JComboBox.getSelectedItem() returns a value that is wrapped by Object type so you have to cast it accordingly.

Syntax:

YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();

How to remove element from an array in JavaScript?

Typescript solution that does not mutate original array

function removeElementAtIndex<T>(input: T[], index: number) {
  return input.slice(0, index).concat(input.slice(index + 1));
}

Finding Variable Type in JavaScript

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

What's better at freeing memory with PHP: unset() or $var = null

For the record, and excluding the time that it takes:

<?php
echo "<hr>First:<br>";
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      
echo memory_get_peak_usage() . "<br>\n"; 
echo "<hr>Unset:<br>";
unset($x);
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      
echo memory_get_peak_usage() . "<br>\n"; 
echo "<hr>Null:<br>";
$x=null;
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      
echo memory_get_peak_usage() . "<br>\n";

echo "<hr>function:<br>";
function test() {
    $x = str_repeat('x', 80000);
}
echo memory_get_usage() . "<br>\n";      
echo memory_get_peak_usage() . "<br>\n"; 

echo "<hr>Reasign:<br>";
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      
echo memory_get_peak_usage() . "<br>\n"; 

It returns

First:
438296
438352
Unset:
438296
438352
Null:
438296
438352
function:
438296
438352
Reasign:
438296
520216 <-- double usage.

Conclusion, both null and unset free memory as expected (not only at the end of the execution). Also, reassigning a variable holds the value twice at some point (520216 versus 438352)

passing form data to another HTML page

Another option is to use "localStorage". You can easealy request the value with javascript in another page.

On the first page, you use the following snippet of javascript code to set the localStorage:

<script>    
   localStorage.setItem("serialNumber", "abc123def456");
</script>

On the second page, you can retrieve the value with the following javascript code snippet:

<script>    
   console.log(localStorage.getItem("serialNumber"));
</script>

On Google Chrome You can vizualize the values pressing F12 > Application > Local Storage.

Source: https://www.w3schools.com/jsref/prop_win_localstorage.asp

Drop a temporary table if it exists

What you asked for is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##CLIENTS_KEYWORD

       CREATE TABLE ##CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
    BEGIN
       DROP TABLE ##TEMP_CLIENTS_KEYWORD

       CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)

    END
ELSE
   CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##CLIENTS_KEYWORD

CREATE TABLE ##CLIENTS_KEYWORD(client_id int) 

IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
   DROP TABLE ##TEMP_CLIENTS_KEYWORD

CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int) 

"Insufficient Storage Available" even there is lot of free space in device memory

I also had this issue while installating an app after I had uninstalled that. I resolved downloading Lucky Patcher and then click on menu - troubleshooting - remove fixes and backups (insufficient storage available). Please notice you need your device to be rooted.

What is an .inc and why use it?

It's just a way for the developer to be able to easily identify files which are meant to be used as includes. It's a popular convention. It does not have any special meaning to PHP, and won't change the behaviour of PHP or the script itself.

How to use MySQL dump from a remote machine

This topic shows up on the first page of my google result, so here's a little useful tip for new comers.

You could also dump the sql and gzip it in one line:

mysqldump -u [username] -p[password] [database_name] | gzip > [filename.sql.gz]

Algorithm to generate all possible permutations of a list?

Wikipedia's answer for "lexicographic order" seems perfectly explicit in cookbook style to me. It cites a 14th century origin for the algorithm!

I've just written a quick implementation in Java of Wikipedia's algorithm as a check and it was no trouble. But what you have in your Q as an example is NOT "list all permutations", but "a LIST of all permutations", so wikipedia won't be a lot of help to you. You need a language in which lists of permutations are feasibly constructed. And believe me, lists a few billion long are not usually handled in imperative languages. You really want a non-strict functional programming language, in which lists are a first-class object, to get out stuff while not bringing the machine close to heat death of the Universe.

That's easy. In standard Haskell or any modern FP language:

-- perms of a list
perms :: [a] -> [ [a] ]
perms (a:as) = [bs ++ a:cs | perm <- perms as, (bs,cs) <- splits perm]
perms []     = [ [] ]

and

-- ways of splitting a list into two parts
splits :: [a] -> [ ([a],[a]) ]
splits []     = [ ([],[]) ]
splits (a:as) = ([],a:as) : [(a:bs,cs) | (bs,cs) <- splits as]

Types in MySQL: BigInt(20) vs Int(20)

I wanted to add one more point is, if you are storing a really large number like 902054990011312 then one can easily see the difference of INT(20) and BIGINT(20). It is advisable to store in BIGINT.

How to develop Desktop Apps using HTML/CSS/JavaScript?

CEF offers lot of flexibility and options for customisation. But if the intent is to develop quickly node-webkit is also a good option. Node-web kit also offers ability to call node modules directly from DOM.

If there aren't any native modules to integrate Node-Webkit can offer better mileage. With native modules C/C++ or even C# it is better with CEF.

AngularJS passing data to $http.get request

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}

Difference between using bean id and name in Spring configuration file

From the Spring reference, 3.2.3.1 Naming Beans:

Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

So basically the id attribute conforms to the XML id attribute standards whereas name is a little more flexible. Generally speaking, I use name pretty much exclusively. It just seems more "Spring-y".

Visual Studio C# IntelliSense not automatically displaying

I had the file excluded from the project so i was not able to debug and have intellisense on that file. Including the file back into the project solved my problem! :)

Check if a string is a palindrome

The various provided answers are wrong for numerous reasons, primarily from misunderstanding what a palindrome is. The majority only properly identify a subset of palindromes.

From Merriam-Webster

A word, verse, or sentence (such as "Able was I ere I saw Elba")

And from Wordnik

A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!

Consider non-trivial palindromes such as "Malayalam" (it's a proper language, so naming rules apply, and it should be capitalized), or palindromic sentences such as "Was it a car or a cat I saw?" or "No 'X' in Nixon".

These are recognized palindromes in any literature.

I'm lifting the thorough solution from a library providing this kind of stuff that I'm the primary author of, so the solution works for both String and ReadOnlySpan<Char> because that's a requirement I've imposed on the library. The solution for purely String will be easy to determine from this, however.

public static Boolean IsPalindrome(this String @string) =>
    !(@string is null) && @string.AsSpan().IsPalindrome();

public static Boolean IsPalindrome(this ReadOnlySpan<Char> span) {
    // First we need to build the string without any punctuation or whitespace or any other
    // unrelated-to-reading characters.
    StringBuilder builder = new StringBuilder(span.Length);
    foreach (Char s in span) {
        if (!(s.IsControl()
            || s.IsPunctuation()
            || s.IsSeparator()
            || s.IsWhiteSpace()) {
            _ = builder.Append(s);
        }
    }
    String prepped = builder.ToString();
    String reversed = prepped.Reverse().Join();
    // Now actually check it's a palindrome
    return String.Equals(prepped, reversed, StringComparison.CurrentCultureIgnoreCase);
}

You're going to want variants of this that accept a CultureInfo parameter as well, when you're testing a specific language rather than your own language, by instead calling .ToUpper(cultureInfo) on prepped.

And here's proof from the projects unit tests that it works.

unit test results

Java: Date from unix timestamp

tl;dr

Instant.ofEpochSecond( 1_280_512_800L )

2010-07-30T18:00:00Z

java.time

The new java.time framework built into Java 8 and later is the successor to Joda-Time.

These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.

Instant instant = Instant.ofEpochSecond( 1_280_512_800L );

instant.toString(): 2010-07-30T18:00:00Z

See that code run live at IdeOne.com.

Table of date-time types in Java, both modern and legacy

Asia/Kabul or Asia/Tehran time zones ?

You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).

If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.

ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
ZonedDateTime zdt = instant.atZone( z );  // Same moment, same point on timeline, but seen as different wall-clock time.

2010-07-30T22:30+04:30[Asia/Tehran]

Converting from java.time to legacy classes

You should stick with the new java.time classes. But you can convert to old if required.

java.util.Date date = java.util.Date.from( instant );

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).

DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );

Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.

java.util.Date date = dateTime.toDate();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

jQuery append text inside of an existing paragraph tag

Try this

$('#add_here').text('new-dynamic-text');

how to access master page control from content page

In Content page you can access the label and set the text such as

Here 'lblStatus' is the your master page label ID

Label lblMasterStatus = (Label)Master.FindControl("lblStatus");

lblMasterStatus.Text  = "Meaasage from content page";

what is the unsigned datatype?

in C, unsigned is a shortcut for unsigned int.

You have the same for long that is a shortcut for long int

And it is also possible to declare a unsigned long (it will be a unsigned long int).

This is in the ANSI standard

AngularJS ng-style with a conditional expression

I am doing like below for multiple and independent conditions and it works like charm:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

MySQL: Fastest way to count number of rows

Great question, great answers. Here's a quick way to echo the results if anyone is reading this page and missing that part:

$counter = mysql_query("SELECT COUNT(*) AS id FROM table");
$num = mysql_fetch_array($counter);
$count = $num["id"];
echo("$count");

How to get current user in asp.net core

Simple way that works and I checked.

private readonly UserManager<IdentityUser> _userManager;
public CompetitionsController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

var user = await _userManager.GetUserAsync(HttpContext.User);

then you can all the properties of this variables like user.Email. I hope this would help someone.

Edit:

It's an apparently simple thing but bit complicated cause of different types of authentication systems in ASP.NET Core. I update cause some people are getting null.

For JWT Authentication (Tested on ASP.NET Core v3.0.0-preview7):

var email = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;

var user = await _userManager.FindByEmailAsync(email);

How do I remove the last comma from a string using PHP?

Try the below code:

$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);

Use this code to remove the last character of the string.

How do I detect a page refresh using jquery?

if you want to bookkeep some variable before page refresh

$(window).on('beforeunload', function(){
    // your logic here
});

if you want o load some content base on some condition

$(window).on('load', function(){
    // your logic here`enter code here`
});

Get HTML5 localStorage keys

You can use the localStorage.key(index) function to return the string representation, where index is the nth object you want to retrieve.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

How to parse XML using jQuery?

I went the way of jQuery's .parseXML() however found that the XML path syntax of 'Page[Name="test"] > controls > test' wouldn't work (if anyone knows why please shout out!).

Instead I chained together the individual .find() results into something that looked like this:

$xmlDoc.find('Page[Name="test"]')
       .find('contols')
       .find('test')

The result achieves the same as what I would expect the one shot find.

How to use a class object in C++ as a function parameter

If you want to pass class instances (objects), you either use

 void function(const MyClass& object){
   // do something with object  
 }

or

 void process(MyClass& object_to_be_changed){
   // change member variables  
 }

On the other hand if you want to "pass" the class itself

template<class AnyClass>
void function_taking_class(){
   // use static functions of AnyClass
   AnyClass::count_instances();
   // or create an object of AnyClass and use it
   AnyClass object;
   object.member = value;
}
// call it as 
function_taking_class<MyClass>();
// or 
function_taking_class<MyStruct>();

with

class MyClass{
  int member;
  //...
};
MyClass object1;

How to delete a column from a table in MySQL

To delete column use this,

ALTER TABLE `tbl_Country` DROP `your_col`

Android ACTION_IMAGE_CAPTURE Intent

to have the camera write to sdcard but keep in a new Album on the gallery app I use this :

 File imageDirectory = new File("/sdcard/signifio");
          String path = imageDirectory.toString().toLowerCase();
           String name = imageDirectory.getName().toLowerCase();


            ContentValues values = new ContentValues(); 
            values.put(Media.TITLE, "Image"); 
            values.put(Images.Media.BUCKET_ID, path.hashCode());
            values.put(Images.Media.BUCKET_DISPLAY_NAME,name);

            values.put(Images.Media.MIME_TYPE, "image/jpeg");
            values.put(Media.DESCRIPTION, "Image capture by camera");
           values.put("_data", "/sdcard/signifio/1111.jpg");
         uri = getContentResolver().insert( Media.EXTERNAL_CONTENT_URI , values);
            Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); 

            i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

            startActivityForResult(i, 0); 

Please note that you will need to generate a unique filename every time and replace teh 1111.jpg that I wrote. This was tested with nexus one. the uri is declared in the private class , so on activity result I am able to load the image from the uri to imageView for preview if needed.

Use of min and max functions in C++

As you noted yourself, fmin and fmax were introduced in C99. Standard C++ library doesn't have fmin and fmax functions. Until C99 standard library gets incorporated into C++ (if ever), the application areas of these functions are cleanly separated. There's no situation where you might have to "prefer" one over the other.

You just use templated std::min/std::max in C++, and use whatever is available in C.

Determine the process pid listening on a certain port

Syntax:

kill -9 $(lsof -t -i:portnumber)

Example: To kill the process running at port 4200, run following command

kill -9 $(lsof -t -i:4200)

Tested in Ubuntu.

Calling a user defined function in jQuery

If you want to call a normal function via a jQuery event, you can do it like this:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#btnSun').click(myFunction);_x000D_
});_x000D_
_x000D_
function myFunction() {_x000D_
  alert('hi');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnSun">Say hello!</button>
_x000D_
_x000D_
_x000D_

How to check if element is visible after scrolling?

Here's my pure JavaScript solution that works if it's hidden inside a scrollable container too.

Demo here (try resizing the window too)

var visibleY = function(el){
  var rect = el.getBoundingClientRect(), top = rect.top, height = rect.height, 
    el = el.parentNode
  // Check if bottom of the element is off the page
  if (rect.bottom < 0) return false
  // Check its within the document viewport
  if (top > document.documentElement.clientHeight) return false
  do {
    rect = el.getBoundingClientRect()
    if (top <= rect.bottom === false) return false
    // Check if the element is out of view due to a container scrolling
    if ((top + height) <= rect.top) return false
    el = el.parentNode
  } while (el != document.body)
  return true
};

EDIT 2016-03-26: I've updated the solution to account for scrolling past the element so it's hidden above the top of the scroll-able container. EDIT 2018-10-08: Updated to handle when scrolled out of view above the screen.

The difference between the Runnable and Callable interfaces in Java

Callable and Runnable both is similar to each other and can use in implementing thread. In case of implementing Runnable you must implement run() method but in case of callable you must need to implement call() method, both method works in similar ways but callable call() method have more flexibility.There is some differences between them.

Difference between Runnable and callable as below--

1) The run() method of runnable returns void, means if you want your thread return something which you can use further then you have no choice with Runnable run() method. There is a solution 'Callable', If you want to return any thing in form of object then you should use Callable instead of Runnable. Callable interface have method 'call()' which returns Object.

Method signature - Runnable->

public void run(){}

Callable->

public Object call(){}

2) In case of Runnable run() method if any checked exception arises then you must need to handled with try catch block, but in case of Callable call() method you can throw checked exception as below

 public Object call() throws Exception {}

3) Runnable comes from legacy java 1.0 version, but callable came in Java 1.5 version with Executer framework.

If you are familiar with Executers then you should use Callable instead of Runnable.

Hope you understand.

Stash only one file out of multiple files that have changed with Git?

Save the following code to a file, for example, named stash. Usage is stash <filename_regex>. The argument is the regular expression for the full path of the file. For example, to stash a/b/c.txt, stash a/b/c.txt or stash .*/c.txt, etc.

$ chmod +x stash
$ stash .*.xml
$ stash xyz.xml

Code to copy into the file:

#! /usr/bin/expect --
log_user 0
set filename_regexp [lindex $argv 0]

spawn git stash -p

for {} 1 {} {
  expect {
    -re "diff --git a/($filename_regexp) " {
      set filename $expect_out(1,string)
    }
    "diff --git a/" {
      set filename ""
    }
    "Stash this hunk " {
      if {$filename == ""} {
        send "n\n"
      } else {
        send "a\n"
        send_user "$filename\n"
      }
    }
    "Stash deletion " {
      send "n\n"
    }
    eof {
      exit
    }
  }
}

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Word wrap for a label in Windows Forms

I had to find a quick solution, so I just used a TextBox with those properties:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

Another Repeated column in mapping for entity error

The message is clear: you have a repeated column in the mapping. That means you mapped the same database column twice. And indeed, you have:

@Column(nullable=false)
private Long customerId;

and also:

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer")
private Customer customer;

(and the same goes for productId/product).

You shouldn't reference other entities by their ID, but by a direct reference to the entity. Remove the customerId field, it's useless. And do the same for productId. If you want the customer ID of a sale, you just need to do this:

sale.getCustomer().getId()

How to hide a TemplateField column in a GridView

try this

.hiddencol
    {
        display:none;
    }
    .viscol
    {
        display:block;
    }

add following code on RowCreated Event of GridView

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         e.Row.Cells[0].CssClass = "hiddencol";
     }
     else if (e.Row.RowType == DataControlRowType.Header)
     {
         e.Row.Cells[0].CssClass = "hiddencol";
     }
}

Turn a simple socket into an SSL socket

OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)

If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html

How to create table using select query in SQL Server?

An example statement that uses a sub-select :

select * into MyNewTable
from
(
select 
  * 
from 
[SomeOtherTablename]
where 
  EventStartDatetime >= '01/JAN/2018' 
)
) mysourcedata
;

note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.

The database should reply with a message like: (9999 row(s) affected)

Possible cases for Javascript error: "Expected identifier, string or number"

This error occurs when we add or missed to remove a comma at the end of array or in function code. It is necessary to observe the entire code of a web page for such error.

I got it in a Facebook app code while I was coding for a Facebook API.

<div id='fb-root'>
    <script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'</script>
    <script type='text/javascript'>
          window.fbAsyncInit = function() {
             FB.init({appId:'".$appid."', status: true, cookie: true, xfbml: true});            
             FB.Canvas.setSize({ width: 800 , height: 860 , }); 
                                                       // ^ extra comma here
          };
    </script>

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

What does template <unsigned int N> mean?

Yes, it is a non-type parameter. You can have several kinds of template parameters

  • Type Parameters.
    • Types
    • Templates (only classes and alias templates, no functions or variable templates)
  • Non-type Parameters
    • Pointers
    • References
    • Integral constant expressions

What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:

Template type parameter:

template<typename T>
struct Container {
    T t;
};

// pass type "long" as argument.
Container<long> test;

Template integer parameter:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

Template pointer parameter (passing a pointer to a function)

template<void (*F)()>
struct FunctionWrapper {
    static void call_it() { F(); }
};

// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;

Template reference parameter (passing an integer)

template<int &A>
struct SillyExample {
    static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

Template template parameter.

template<template<typename T> class AllocatePolicy>
struct Pool {
    void allocate(size_t n) {
        int *p = AllocatePolicy<int>::allocate(n);
    }
};

// pass the template "allocator" as argument. 
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:

template<unsigned int SIZE = 3>
struct Vector {
    unsigned char buffer[SIZE];
};

Vector<> test;

Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:

template<>
struct Vector<3> {
    // alternative definition for SIZE == 3
};

Android - How to regenerate R class?

Try to add a new "Android XML file" to, for example, the /res/layout folder. This might cause the plugin to to regenerate the R class.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

Hope this will help...

mdpi is the reference density -- that is, 1 px on an mdpi display is equal to 1 dip. The ratio for asset scaling is:

ldpi | mdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
0.75 | 1    | 1.5  | 2     | 3      | 4

Although you don't really need to worry about tvdpi unless you're developing specifically for Google TV or the original Nexus 7 -- but even Google recommends simply using hdpi assets. You probably don't need to worry about xxhdpi either (although it never hurts, and at least the launcher icon should be provided at xxhdpi), and xxxhdpi is just a constant in the source code right now (no devices use it, nor do I expect any to for a while, if ever), so it's safe to ignore as well.

What this means is if you're doing a 48dip image and plan to support up to xhdpi resolution, you should start with a 96px image (144px if you want native assets for xxhdpi) and make the following images for the densities:

ldpi    | mdpi    | hdpi    | xhdpi     | xxhdpi    | xxxhdpi
36 x 36 | 48 x 48 | 72 x 72 | 96 x 96   | 144 x 144 | 192 x 192

And these should display at roughly the same size on any device, provided you've placed these in density-specific folders (e.g. drawable-xhdpi, drawable-hdpi, etc.)

For reference, the pixel densities for these are:

ldpi  | mdpi  | hdpi  | xhdpi  | xxhdpi  | xxxhdpi
120   | 160   | 240   | 320    | 480     | 640

how to empty recyclebin through command prompt?

You can use this PowerShell command.

Clear-RecycleBin -Force

Note: If you want a confirmation prompt, remove the -Force flag

How to export and import environment variables in windows?

A PowerShell script based on @Mithrl's answer

# export_env.ps1
$Date = Get-Date
$DateStr = '{0:dd-MM-yyyy}' -f $Date

mkdir -Force $PWD\env_exports | Out-Null

regedit /e "$PWD\env_exports\user_env_variables[$DateStr].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "$PWD\env_exports\global_env_variables[$DateStr].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

CreateProcess error=2, The system cannot find the file specified

I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

I got an error. But if I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

everything was OK.

Calculate a Running Total in SQL Server

SELECT TOP 25   amount, 
    (SELECT SUM(amount) 
    FROM time_detail b 
    WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a

You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.

How can I modify the size of column in a MySQL table?

Have you tried this?

ALTER TABLE <table_name> MODIFY <col_name> VARCHAR(65353);

This will change the col_name's type to VARCHAR(65353)

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.

How to use Java property files?

By default, Java opens it in the working directory of your application (this behavior actually depends on the OS used). To load a file, do:

Properties props = new java.util.Properties();
FileInputStream fis new FileInputStream("myfile.txt");
props.load(fis)

As such, any file extension can be used for property file. Additionally, the file can also be stored anywhere, as long as you can use a FileInputStream.

On a related note if you use a modern framework, the framework may provide additionnal ways of opening a property file. For example, Spring provide a ClassPathResource to load a property file using a package name from inside a JAR file.

As for iterating through the properties, once the properties are loaded they are stored in the java.util.Properties object, which offer the propertyNames() method.

What is a 'multi-part identifier' and why can't it be bound?

It's probably a typo. Look for the places in your code where you call [schema].[TableName] (basically anywhere you reference a field) and make sure everything is spelled correctly.

Personally, I try to avoid this by using aliases for all my tables. It helps tremendously when you can shorten a long table name to an acronym of it's description (i.e. WorkOrderParts -> WOP), and also makes your query more readable.

Edit: As an added bonus, you'll save TONS of keystrokes when all you have to type is a three or four-letter alias vs. the schema, table, and field names all together.

Remove carriage return from string

How about:

string s = orig.Replace("\n","").Replace("\r","");

which should handle the common line-endings.

Alternatively, if you have that string hard-coded or are assembling it at runtime - just don't add the newlines in the first place.

How to sum digits of an integer in java?

without mapping ? the quicker lambda solution

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );

…or same with the slower % operator

Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );


…or Unicode compliant

Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );

View's SELECT contains a subquery in the FROM clause

As the more recent MySQL documentation on view restrictions says:

Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.

This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.

However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.

Passing arguments forward to another javascript function

If you want to only pass certain arguments, you can do so like this:

Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')

Foo.js

bar (obj, method, ...args) {
  obj[method](...args)
}

obj and method are used by the bar() method, while the rest of args are passed to the actual call.

C# - Create SQL Server table programmatically

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommend
{
    class sqlcreateapp
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Table Created Successfully...");
                conn.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
            }
            Console.ReadKey();
        }
    }
}

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

Remove all occurrences of a value from a list?

a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)

Perhaps not the most pythonic but still the easiest for me haha

Add UIPickerView & a Button in Action sheet - How?

Even though this question is old, I'll quickly mention that I've thrown together an ActionSheetPicker class with a convenience function, so you can spawn an ActionSheet with a UIPickerView in one line. It's based on code from answers to this question.

Edit: It now also supports the use of a DatePicker and DistancePicker.


UPD:

This version is deprecated: use ActionSheetPicker-3.0 instead.

animation

How can I set the aspect ratio in matplotlib?

This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.

def forceAspect(ax,aspect=1):
    #aspect is width/height
    scale_str = ax.get_yaxis().get_scale()
    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    if scale_str=='linear':
        asp = abs((xmax-xmin)/(ymax-ymin))/aspect
    elif scale_str=='log':
        asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
    ax.set_aspect(asp)

Obviously you can use any version of log you want, I've used scipy, but numpy or math should be fine.

Link to download apache http server for 64bit windows.

An unofficial 64-bit Windows build is available from Apache Lounge.

access key and value of object using *ngFor

You could create a custom pipe to return the list of key for each element. Something like that:

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

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push(key);
    }
    return keys;
  }
}

and use it like that:

<tr *ngFor="let c of content">           
  <td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>

Edit

You could also return an entry containing both key and value:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

and use it like that:

<span *ngFor="let entry of content | keys">           
  Key: {{entry.key}}, value: {{entry.value}}
</span>

How do I get the current date and current time only respectively in Django?

 import datetime

Current Date and time

     print(datetime.datetime.now())
     #2019-09-08 09:12:12.473393

Current date only

     print(datetime.date.today())
     #2019-09-08

Current year only

     print(datetime.date.today().year)
     #2019

Current month only

     print(datetime.date.today().month)
     #9

Current day only

     print(datetime.date.today().day)
     #8

jQuery datepicker set selected date, on the fly

setDate only seems to be an issue with an inline datepicker used in jquery UI, the specific error is InternalError: too much recursion.

Importing modules from parent folder

You could use relative imports (python >= 2.5):

from ... import nib

(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports

EDIT: added another dot '.' to go up two packages

How to use QueryPerformanceCounter?

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"\n";
    return 0;
}

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

to

PCFreq = double(li.QuadPart);

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

But really it's about convenience since it returns a double.

Reading a .txt file using Scanner class in Java

No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.

for (int i =0 ; sc.HasNextLine();i++)
{
    array[i] = sc.NextInt();
}

Something to this effect will keep setting values of the array to the next integer read.

Than another for loop can display the numbers in the array.

for (int x=0;x< array.length ; x++)
{
    System.out.println("array[x]");
}

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

Can functions be passed as parameters?

Here is a simple example:

    package main

    import "fmt"

    func plusTwo() (func(v int) (int)) {
        return func(v int) (int) {
            return v+2
        }
    }

    func plusX(x int) (func(v int) (int)) {
       return func(v int) (int) {
           return v+x
       }
    }

    func main() {
        p := plusTwo()
        fmt.Printf("3+2: %d\n", p(3))

        px := plusX(3)
        fmt.Printf("3+3: %d\n", px(3))
    }

Pandas DataFrame: replace all values in a column, based on condition

We can update the First Season column in df with the following syntax:

df['First Season'] = expression_for_new_values

To map the values in First Season we can use pandas‘ .map() method with the below syntax:

data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How to pass arguments to a Button command in Tkinter?

You need to use lambda:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

phonegap open link in browser

Like this :

<a href="#" onclick="window.open('https://www.nbatou.com', '_system'); return false;">https://www.nbatou.com</a>

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

Convert JSON to Map

JSON to Map always gonna be a string/object data type. i haved GSON lib from google.

works very well and JDK 1.5 is the min requirement.

to remove first and last element in array

To remove the first and last element of an array is by using the built-in method of an array i.e shift() and pop() the fruits.shift() get the first element of the array as "Banana" while fruits.pop() get the last element of the array as "Mango". so the remaining element of the array will be ["Orange", "Apple"]

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How to only get file name with Linux 'find'?

If your find doesn't have a -printf option you can also use basename:

find ./dir1 -type f -exec basename {} \;

How to run (not only install) an android application using .apk file?

First to install your app:

adb install -r path\ProjectName.apk

The great thing about the -r is it works even if it wasn’t already installed.

To launch MainActivity, so you can launch it like:

adb shell am start -n com.other.ProjectName/.MainActivity

How to style the parent element when hovering a child element?

there is no CSS selector for selecting a parent of a selected child.

you could do it with JavaScript

React-Router: No Not Found Route?

According to the documentation, the route was found, even though the resource wasn't.

Note: This is not intended to be used for when a resource is not found. There is a difference between the router not finding a matched path and a valid URL that results in a resource not being found. The url courses/123 is a valid url and results in a matched route, therefore it was "found" as far as routing is concerned. Then, if we fetch some data and discover that the course 123 does not exist, we do not want to transition to a new route. Just like on the server, you go ahead and serve the url but render different UI (and use a different status code). You shouldn't ever try to transition to a NotFoundRoute.

So, you could always add a line in the Router.run() before React.render() to check if the resource is valid. Just pass a prop down to the component or override the Handler component with a custom one to display the NotFound view.

Get the IP address of the machine

I do not think there is a definitive right answer to your question. Instead there is a big bundle of ways how to get close to what you wish. Hence I will provide some hints how to get it done.

If a machine has more than 2 interfaces (lo counts as one) you will have problems to autodetect the right interface easily. Here are some recipes on how to do it.

The problem, for example, is if hosts are in a DMZ behind a NAT firewall which changes the public IP into some private IP and forwards the requests. Your machine may have 10 interfaces, but only one corresponds to the public one.

Even autodetection does not work in case you are on double-NAT, where your firewall even translates the source-IP into something completely different. So you cannot even be sure, that the default route leads to your interface with a public interface.

Detect it via the default route

This is my recommended way to autodetect things

Something like ip r get 1.1.1.1 usually tells you the interface which has the default route.

If you want to recreate this in your favourite scripting/programming language, use strace ip r get 1.1.1.1 and follow the yellow brick road.

Set it with /etc/hosts

This is my recommendation if you want to stay in control

You can create an entry in /etc/hosts like

80.190.1.3 publicinterfaceip

Then you can use this alias publicinterfaceip to refer to your public interface.

Sadly haproxy does not grok this trick with IPv6

Use the environment

This is a good workaround for /etc/hosts in case you are not root

Same as /etc/hosts. but use the environment for this. You can try /etc/profile or ~/.profile for this.

Hence if your program needs a variable MYPUBLICIP then you can include code like (this is C, feel free to create C++ from it):

#define MYPUBLICIPENVVAR "MYPUBLICIP"

const char *mypublicip = getenv(MYPUBLICIPENVVAR);

if (!mypublicip) { fprintf(stderr, "please set environment variable %s\n", MYPUBLICIPENVVAR); exit(3); }

So you can call your script/program /path/to/your/script like this

MYPUBLICIP=80.190.1.3 /path/to/your/script

this even works in crontab.

Enumerate all interfaces and eliminate those you do not want

The desperate way if you cannot use ip

If you do know what you do not want, you can enumerate all interfaces and ignore all the false ones.

Here already seems to be an answer https://stackoverflow.com/a/265978/490291 for this approach.

Do it like DLNA

The way of the drunken man who tries to drown himself in alcohol

You can try to enumerate all the UPnP gateways on your network and this way find out a proper route for some "external" thing. This even might be on a route where your default route does not point to.

For more on this perhaps see https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol

This gives you a good impression which one is your real public interface, even if your default route points elsewhere.

There are even more

Where the mountain meets the prophet

IPv6 routers advertise themselves to give you the right IPv6 prefix. Looking at the prefix gives you a hint about if it has some internal IP or a global one.

You can listen for IGMP or IBGP frames to find out some suitable gateway.

There are less than 2^32 IP addresses. Hence it does not take long on a LAN to just ping them all. This gives you a statistical hint on where the majority of the Internet is located from your point of view. However you should be a bit more sensible than the famous https://de.wikipedia.org/wiki/SQL_Slammer

ICMP and even ARP are good sources for network sideband information. It might help you out as well.

You can use Ethernet Broadcast address to contact to all your network infrastructure devices which often will help out, like DHCP (even DHCPv6) and so on.

This additional list is probably endless and always incomplete, because every manufacturer of network devices is busily inventing new security holes on how to auto-detect their own devices. Which often helps a lot on how to detect some public interface where there shouln't be one.

'Nuff said. Out.

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Virtual network interface in Mac OS X

Go to Network Preferences.

At the bottom of the list of network adapters, click the + icons

Select the existing interface that you want to arp (say Ethernet 1), and give the Service Name that you want for the new port (say Ethernet 1.1) then press create.

Now you have the new virtual interface in the gui and can manage IP addresses etc it in the normal way.

ifconfig -a will confirm that you have multiple IPs on the interface, and these will still be there when you reboot.

Its a Mac. Don't fight it, do it the easy way.

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

Thanks to this post, I found an easier answer:

  1. Open Sql Server Management Studio

  2. Go to object Explorer -> Security -> Logins

  3. Right click on the login and select properties

  4. And in the properties window change the default database and click OK.

How do I disable "missing docstring" warnings at a file-level in Pylint?

It is nice for a Python module to have a docstring, explaining what the module does, what it provides, examples of how to use the classes. This is different from the comments that you often see at the beginning of a file giving the copyright and license information, which IMO should not go in the docstring (some even argue that they should disappear altogether, see e.g. Get Rid of Source Code Templates)

With Pylint 2.4 and above, you can differentiate between the various missing-docstring by using the three following sub-messages:

  • C0114 (missing-module-docstring)
  • C0115 (missing-class-docstring)
  • C0116 (missing-function-docstring)

So the following .pylintrc file should work:

[MASTER]
disable=
    C0114, # missing-module-docstring

For previous versions of Pylint, it does not have a separate code for the various place where docstrings can occur, so all you can do is disable C0111. The problem is that if you disable this at module scope, then it will be disabled everywhere in the module (i.e., you won't get any C line for missing function / class / method docstring. Which arguably is not nice.

So I suggest adding that small missing docstring, saying something like:

"""
high level support for doing this and that.
"""

Soon enough, you'll be finding useful things to put in there, such as providing examples of how to use the various classes / functions of the module which do not necessarily belong to the individual docstrings of the classes / functions (such as how these interact, or something like a quick start guide).

connecting MySQL server to NetBeans

Follow these 2 steps:

STEP 1 :

Follow these steps using the Services Tab:

  1. Right click on Database
  2. Create new Connection

Customize the New COnnection as follows:

  1. Connector Name: MYSQL (Connector/J Driver)
  2. Host: localhost
  3. Port: 3306
  4. Database: mysql ( mysql is the default or enter your database name)
  5. Username: enter your database username
  6. Password: enter your database password
  7. JDBC URL: jdbc:mysql://localhost:3306/mysql
  8. CLick Finish button

NB: DELETE the ?zeroDateTimeBehaviour=convertToNull part in the URL. Instead of mysql in the URL, you should see your database name)


STEP 2 :

  1. Right click on MySQL Server at localhost:3306:[username](...)
  2. Select Properties... from the shortcut menu

In the "MySQL Server Properties" dialog select the "Admin Properties" tab Enter the following in the textboxes specified:

For Linux users :

  1. Path to start command: /usr/bin/mysql
  2. Arguments: /etc/init.d/mysql start
  3. Path to Stop command: /usr/bin/mysql
  4. Arguments: /etc/init.d/mysql stop

For MS Windows users :

NOTE: Optional:

In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.

Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a command-line tool and not ideal for use with the IDE.

Citations:
https://netbeans.org/kb/docs/ide/mysql.html?print=yes
http://javawebaction.blogspot.com/2013/04/how-to-register-mysql-database-server.html


We will use MySQL Workbench in this example. Please use the path of your installation if you have MySQL workbench and the path to MySQL.

  1. Path/URL to admin tool: C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\MySQLWorkbench.exe
  2. Arguments: (Leave blank)
  3. Path to start command: C:\mysql\bin\mysqld (OR C:\mysql\bin\mysqld.exe)
  4. Arguments: (Leave blank)
  5. Path to Stop command: C:\mysql\bin\mysqladmin (OR C:\mysql\bin\mysqladmin.exe )
  6. Arguments: -u root shutdown (Try -u root stop)

Possible exampes of MySQL bin folder locations for Windows Users:

  • C:\mysql\bin
  • C:\Program Files\MySQL\MySQL Server 5.1\bin\
  • Installation Folder: ~\xampp\mysql\bin

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

Add this line to the file xampp\phpMyAdmin\config.inc:

$cfg['Servers'][$i]['port'] = '3307';

Here, my port is 3307, you can change it to yours.

How do I check if a list is empty?

len() is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.

JavaScript has a similar notion of truthy/falsy.

Disable eslint rules for folder

The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:

{
    "env": {},
    "extends": [],
    "parser": "",
    "plugins": [],
    "rules": {},
    "overrides": [
      {
        "files": ["test/*.spec.js"], // Or *.test.js
        "rules": {
          "require-jsdoc": "off"
        }
      }
    ],
    "settings": {}
}

SQL Inner join more than two tables

Try this Here the syntax is

SELECT table1 .columnName, table3 .columnName 
   FROM table1 
     inner join table2 
          ON table1.primarykey = table2.foreignkey 
     inner join table3 
          ON table2.primarykey = table3.foreignkey

for example: Select SalesHeader.invoiceDate,ActualSales,DeptName,tblInvDepartment.DeptCode ,LocationCode from SalesDetail Inner Join SalesHeader on SalesDetail.InvoiceNo = SalesHeader.InvoiceNo inner join tblInvDepartment on tblInvDepartment.DeptCode = SalesDetail.DeptCode

fatal: could not read Username for 'https://github.com': No such file or directory

What worked for me is to change the access of the Git repository from private to public.

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

Date format in the json output using spring boot

If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.dateFormat(new ISO8601DateFormat());        
        }           
    };
}

How to Update a Component without refreshing full page - Angular

To update component

 @Injectable()
    export class LoginService{
    private isUserLoggedIn: boolean = false;

    public setLoggedInUser(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
    this.isUserLoggedIn= flag;
    }


public getUserLoggedIn(): boolean {
return this.isUserLoggedIn;
}

Login Component ts
            Login Component{
             constructor(public service: LoginService){}

public login(){
service.setLoggedInUser(true);
}
            }
Inside Header component

 Header Component ts
        HeaderComponent {
         constructor(public service: LoginService){}

         public getUserLoggedIn(): boolean { return this.service.getUserLoggedIn()}
        }

template of header component: Check for user sign in here

<button *ngIf="getUserLoggedIn()">Sign Out</button>
<button *ngIf="!getUserLoggedIn()">Sign In</button>

You can use many approach like show hide using ngIf

App Component ts
AppComponent {
 public showHeader: boolean = true;
}
App Component html
<div *ngIf='showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
<app-header></app-header>
</div>
<router-outlet></router-outlet>
<app-footer></app-footer>

You can also use service

@Injectable()
export class AppService {
private showHeader: boolean = false;

public setHeader(flag) { // you need set header flag true false from other components on basis of your requirements, header component will be visible as per this flag then
this.showHeader = flag;
}

public getHeader(): boolean {
return this.showHeader;
}
}

App Component.ts
    AppComponent {
     constructor(public service: AppService){}
    }

App Component.html
    <div *ngIf='service.showHeader'> // you show hide on basis of this ngIf and header component always get visible with it's lifecycle hook ngOnInit() called all the time when it get visible
    <app-header></app-header>
    </div>
    <router-outlet></router-outlet>
    <app-footer></app-footer>

How do you use the ? : (conditional) operator in JavaScript?

Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.

condition ? expressionIfTrue : expressionIfFalse

Think of expressionIfTrue as the OG if statement rendering true;
think of expressionIfFalse as the else statement.

Example:

var x = 1;
(x == 1) ? y=x : y=z;

this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

How can I replace newline or \r\n with <br/>?

Try using this:

$description = preg_replace("/\r\n|\r|\n/", '<br/>', $description);

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

php: how to get associative array key from numeric index?

Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,

    function get_key($array, $index){
      $idx=0;
      while($idx!=$index  && next($array)) $idx++;
      if($idx==$index) return key($array);
      else return '';
    }

String Resource new line /n not possible?

I want to expand on this answer. What they meant is this icon:

Editor window button

It opens a "real editor window" instead of the limited-feature text box in the big overview. In that editor window, special chars, linebreaks etc. are allowed and converted to the correct xml "code" when saved

Branch from a previous commit using Git

Select Commit

For Git GUI users you can visualize all the history (if necessary) and then right click on the commit you wish to branch from and enter the branch name.

Enter Branch name

Visualize all the history

no debugging symbols found when using gdb

I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.

I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.

Regular expression to limit number of characters to 10

It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.

Flutter : Vertically center column

Try this one. It centers vertically and horizontally.

Center(
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: children,
  ),
)

jQuery UI dialog box not positioned center screen

Just solved the same problem, the issue was that i did not imported some js files, like widget.js :)

How to get changes from another branch

For other people coming upon this post on google. There are 2 options, either merging or rebasing your branch. Both works differently, but have similar outcomes.

The accepted answer is a rebase. This will take all the commits done to our-team and then apply the commits done to featurex, prompting you to merge them as needed.

One bit caveat of rebasing is that you lose/rewrite your branch history, essentially telling git that your branch did not began at commit 123abc but at commit 456cde. This will cause problems for other people working on the branch, and some remote tools will complain about it. If you are sure about what you are doing though, that's what the --force flag is for.

What other posters are suggesting is a merge. This will take the featurex branch, with whatever state it has and try to merge it with the current state of our-team, prompting you to do one, big, merge commit and fix all the merge errors before pushing to our-team. The difference is that you are applying your featurex commits before the our-team new commits and then fixing the differences. You also do not rewrite history, instead adding one commit to it instead of rewriting those that came before.

Both options are valid and can work in tandem. What is usually (by that I mean, if you are using widespread tools and methodology such as git-flow) done for a feature branch is to merge it into the main branch, often going through a merge-request, and solve all the conflicts that arise into one (or multiple) merge commits.

Rebasing is an interesting option, that may help you fix your branch before eventually going through a merge, and ease the pain of having to do one big merge commit.

How do I check out a remote Git branch?

Please follow the command to create an empty folder. Enter that and use this command:

saifurs-Mini:YO-iOS saifurrahman$ git clone your_project_url
Cloning into 'iPhoneV1'...
remote: Counting objects: 34230, done.
remote: Compressing objects: 100% (24028/24028), done.
remote: Total 34230 (delta 22212), reused 15340 (delta 9324)
Receiving objects: 100% (34230/34230), 202.53 MiB | 294.00 KiB/s, done.
Resolving deltas: 100% (22212/22212), done.
Checking connectivity... done.
saifurs-Mini:YO-iOS saifurrahman$ cd iPhoneV1/
saifurs-Mini:iPhoneV1 saifurrahman$ git checkout 1_4_0_content_discovery
Branch 1_4_0_content_discovery set up to track remote branch 1_4_0_content_discovery from origin.
Switched to a new branch '1_4_0_content_discovery'

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

public static class MyExtension
{
    public static string ToPrettySize(this float Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    public static string ToPrettySize(this int Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    private static string ConvertToPrettySize(float Size, int R)
    {
        float F = Size / 1024f;
        if (F < 1)
        {
            switch (R)
            {
                case 0:
                    return string.Format("{0:0.00} byte", Size);
                case 1:
                    return string.Format("{0:0.00} kb", Size);
                case 2:
                    return string.Format("{0:0.00} mb", Size);
                case 3:
                    return string.Format("{0:0.00} gb", Size);
            }
        }
        return ConvertToPrettySize(F, ++R);
    }
}

Difference between two dates in years, months, days in JavaScript

Some math is in order.

You can subtract one Date object from another in Javascript, and you'll get the difference between them in milisseconds. From this result you can extract the other parts you want (days, months etc.)

For example:

var a = new Date(2010, 10, 1);
var b = new Date(2010, 9, 1);

var c = a - b; // c equals 2674800000,
               // the amount of milisseconds between September 1, 2010
               // and August 1, 2010.

Now you can get any part you want. For example, how many days have elapsed between the two dates:

var days = (a - b) / (60 * 60 * 24 * 1000);
// 60 * 60 * 24 * 1000 is the amount of milisseconds in a day.
// the variable days now equals 30.958333333333332.

That's almost 31 days. You can then round down for 30 days, and use whatever remained to get the amounts of hours, minutes etc.

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

How to make a div fill a remaining horizontal space?

I had a similar issue and came up with the following which worked well

CSS:

.top {
width: auto;
height: 100px;
background-color: black;
border: solid 2px purple;
overflow: hidden;
}
.left {
float:left;
width:100px;
background-color:#ff0000;
padding: 10px;
border: solid 2px black;
}
.right {
width: auto;
background-color:#00FF00;
padding: 10px;
border: solid 2px orange;
overflow: hidden;
}
.content {
margin: auto;
width: 300px;
min-height: 300px;
padding: 10px;
border: dotted 2px gray;
}

HTML:

<div class=top>top </div>
<div>
    <div class="left">left </div>
    <div class="right">
        <div class="content">right </div>
    </div>
</div>

This method won't wrap when the window is shrunk but will auto expand the 'content' area. It will keep a static width for the site menu (left).

And for auto expanding content box and left vertical box(site menu) demo:

https://jsfiddle.net/tidan/332a6qte/

Getting String Value from Json Object Android

If you can use JSONObject library, you could just

    JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
    String result = ja.getJSONObject(0).getString("NeededString");

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

Is it possible to GROUP BY multiple columns using MySQL?

Yes, you can group by multiple columns. For example,

SELECT * FROM table
GROUP BY col1, col2

The results will first be grouped by col1, then by col2. In MySQL, column preference goes from left to right.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

A small work around I used many times

_x000D_
_x000D_
Promise.resolve(data).then(() => {
    console.log( "! changement de la date du composant !" );
    this.dateNow = new Date();
    this.cdRef.detectChanges();
});
_x000D_
_x000D_
_x000D_