Programs & Examples On #Dismax

DisMax is an abbreviation of Disjunction Max, and is a popular query mode with Apache Solr.

Run jQuery function onclick

You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.

$("div.system_box").on('mouseenter', function(){
    //enter
})
.on('mouseleave', function(){
    //leave
});

fiddle

note: do not use hover as that is deprecated

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. First make sure sa is enabled
  2. Change the authontication mode to mixed mode (Window and SQL authentication)
  3. Stop your SQL Server
  4. Restart your SQL Server

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I have found that when you are forced to use the Configuration Manager to run under x86 or anything other than the standard project "out of the box" settings, the IDE creates a bunch of sub directories under the bin folder for the web project.

Once this starts happening, if the Cassini server is running, then the project does not serve properly.

I fixed it by going into the Web Project properties -> Build settings and changing the Output Path to be bin\

Then rebuild and all works as it should.

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

How to use SVN, Branch? Tag? Trunk?

Commit frequency depends on your style of project management. Many people refrain from committing if it'll break the build (or functionality).

Branches can be used in one of two ways, typically: 1) One active branch for development (and the trunk stays stable), or 2) branches for alternate dev paths.

Tags are generally used for identifying releases, so they don't get lost in the mix. The definition of 'release' is up to you.

Git on Windows: How do you set up a mergetool?

For IntelliJ IDEA (Community Edition) 3-way git mergetool configuration in Windows environment (~/.gitconfig)

Cygwin

[mergetool "ideamerge"]
     cmd = C:/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe merge `cygpath -wa $LOCAL` `cygpath -wa $REMOTE` `cygpath -wa $BASE` `cygpath -wa $MERGED`
[merge]
     tool = ideamerge

Msys

[mergetool "ideamerge"]
cmd = "/c/Program\\ Files\\ \\(x86\\)/JetBrains/IntelliJ\\ IDEA\\ Community\\ Edition\\ 14.1.3/bin/idea.exe" merge `~/winpath.sh $LOCAL` `~/winpath.sh $REMOTE` `~/winpath.sh $BASE` `~/winpath.sh $MERGED`
[merge]
 tool = ideamerge

The ~/winpath.sh is to convert paths to Windows on msys and is taken from msys path conversion question on stackoverflow

#! /bin/sh                                                               

function wpath {                                                         
    if [ -z "$1" ]; then                                                 
        echo "$@"                                                        
    else                                                                 
        if [ -f "$1" ]; then                                             
            local dir=$(dirname "$1")                                    
            local fn=$(basename "$1")                                    
            echo "$(cd "$dir"; echo "$(pwd -W)/$fn")" | sed 's|/|\\|g';  
        else                                                             
            if [ -d "$1" ]; then                                         
                echo "$(cd "$1"; pwd -W)" | sed 's|/|\\|g';              
            else                                                         
                echo "$1" | sed 's|^/\(.\)/|\1:\\|g; s|/|\\|g';          
            fi                                                           
        fi                                                               
    fi                                                                   
}                                                                        

wpath "$@" 

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to deal with a slow SecureRandom generator?

I faced same issue. After some Googling with the right search terms, I came across this nice article on DigitalOcean.

haveged is a potential solution without compromising on security.

I am merely quoting the relevant part from the article here.

Based on the HAVEGE principle, and previously based on its associated library, haveged allows generating randomness based on variations in code execution time on a processor. Since it's nearly impossible for one piece of code to take the same exact time to execute, even in the same environment on the same hardware, the timing of running a single or multiple programs should be suitable to seed a random source. The haveged implementation seeds your system's random source (usually /dev/random) using differences in your processor's time stamp counter (TSC) after executing a loop repeatedly

How to install haveged

Follow the steps in this article. https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged

I have posted it here

Using Environment Variables with Vue.js

A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.

Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.

So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

Based on the above, in production, you would be able to get the NODE_ENV variable

mounted() {
  console.log(process.env.NODE_ENV)
}

Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"'
      }
    })
  ]);

} 

Now if you want to add other variables with would be as simple as:

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);
}

I should also note that you seem to need the "''" double quotes for some reason.

So, in Development, I can now access these Environment Variables:

mounted() {
  console.log(process.env.ENDPOINT)
  console.log(process.env.FOO)
}

Here is the whole webpack.config.js just for some context:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'vue-style-loader',
          'css-loader'
        ],
      },      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: ['*', '.js', '.vue', '.json']
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true,
    overlay: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

if (process.env.NODE_ENV === 'development') {

  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"development"',
        ENDPOINT: '"http://localhost:3000"',
        FOO: "'BAR'"
      }
    })
  ]);

}

Open existing file, append a single line

Or you could use File.AppendAllLines(string, IEnumerable<string>)

File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });

Running AMP (apache mysql php) on Android

For me AndroPHP (its an app name) , worked perfectly... see below links

http://gntheprogrammer.blogspot.in/2013/09/how-to-use-your-android-device-as.html

https://doc.tiki.org/AndroPHP

Please follow the steps it will help u .....

Run an OLS regression with Pandas Data Frame

This would require me to reformat the data into lists inside lists, which seems to defeat the purpose of using pandas in the first place.

No it doesn't, just convert to a NumPy array:

>>> data = np.asarray(df)

This takes constant time because it just creates a view on your data. Then feed it to scikit-learn:

>>> from sklearn.linear_model import LinearRegression
>>> lr = LinearRegression()
>>> X, y = data[:, 1:], data[:, 0]
>>> lr.fit(X, y)
LinearRegression(copy_X=True, fit_intercept=True, normalize=False)
>>> lr.coef_
array([  4.01182386e-01,   3.51587361e-04])
>>> lr.intercept_
14.952479503953672

Declare a dictionary inside a static class

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

Copying sets Java

Starting from Java 10:

Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);

Set.copyOf() returns an unmodifiable Set containing the elements of the given Collection.

The given Collection must not be null, and it must not contain any null elements.

How to get correct timestamp in C#

var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

To draw an Underline below the TextView in Android

You can use Kotlin Extension and type your own drawUnderLine method.

fun TextView.drawUnderLine() {
    val text = SpannableString(this.text.toString())
    text.setSpan(UnderlineSpan(), 0, text.length, 0)
    this.text = text
}
yourTextView.drawUnderLine()

How to encode the plus (+) symbol in a URL

Is you want a plus (+) symbol in the body you have to encode it as 2B.

For example: Try this

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

How do I compare two strings in Perl?

And if you'd like to extract the differences between the two strings, you can use String::Diff.

Use a URL to link to a Google map with a marker on it

In May 2017 Google launched the official Google Maps URLs documentation. The Google Maps URLs introduces universal cross-platform syntax that you can use in your applications.

Have a look at the following document:

https://developers.google.com/maps/documentation/urls/guide

You can use URLs in search, directions, map and street view modes.

For example, to show the marker at specified position you can use the following URL:

https://www.google.com/maps/search/?api=1&query=36.26577,-92.54324

For further details please read aforementioned documentation.

You can also file feature requests for this API in Google issue tracker.

Hope this helps!

Found conflicts between different versions of the same dependent assembly that could not be resolved

I have uninstalled Microsoft ASP.NET MVC nuget.org from manage NuGet Packagaes and again re-installed it. While re-installing it resolved all the conflicts related to razor version. Try it .

Get current time in seconds since the Epoch on Linux, Bash

Just to add.

Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).

date -d "Oct 21 1973" +%s


Convert the number of seconds back to date

date --date @120024000


The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date --help). Show the local time for 9AM next Friday on the west coast of the US

date --date='TZ="America/Los_Angeles" 09:00 next Fri'

Better yet, take some time to read the man page http://man7.org/linux/man-pages/man1/date.1.html

How to make (link)button function as hyperlink?

You can use OnClientClick event to call a JavaScript function:

<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />

JavaScript code:

function redirect() {
  location.href = 'page.aspx';
}

But i think the best would be to style a hyperlink with css.

Example :

.button {
  display: block;
  height: 25px;
  background: #f1f1f1;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #e1e1e2;
  color: #000;
  font-weight: bold;
}

Guid is all 0's (zeros)?

Use the static method Guid.NewGuid() instead of calling the default constructor.

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = Guid.NewGuid()
});

Restrict varchar() column to specific values?

You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
    CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DATA_TYPE();

For you problem:

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DECIMAL(Precision, Scale); 

Simplest way to throw an error/exception with a custom message in Swift 2?

Swift 4:

As per:

https://developer.apple.com/documentation/foundation/nserror

if you don't want to define a custom exception, you could use a standard NSError object as follows:

import Foundation

do {
  throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
}
catch let error as NSError {
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
  let uis = error.userInfo 
  print("\tUser info:")
  for (key,value) in uis {
    print("\t\tkey=\(key), value=\(value)")
  }
}

Prints:

Caught NSError: The operation could not be completed, my error domain, 42
    User info:
        key=ui1, value=12
        key=ui2, value=val2

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

How do I check if an array includes a value in JavaScript?

You can use findIndex function to check if an array has a specific value.

arrObj.findIndex(obj => obj === comparedValue) !== -1;

Returns true if arrObj contains comparedValue, false otherwise.

Typescript es6 import module "File is not a module error"

Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.

How to check if a String contains only ASCII?

Or you copy the code from the IDN class.

// to check if a string only contains US-ASCII code point
//
private static boolean isAllASCII(String input) {
    boolean isASCII = true;
    for (int i = 0; i < input.length(); i++) {
        int c = input.charAt(i);
        if (c > 0x7F) {
            isASCII = false;
            break;
        }
    }
    return isASCII;
}

How to load assemblies in PowerShell?

Make sure you have below features are installed in order

  1. Microsoft System CLR Types for SQL Server
  2. Microsoft SQL Server Shared Management Objects
  3. Microsoft Windows PowerShell Extensions

Also you may need to load

Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"

how to create Socket connection in Android?

Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html

Things you need to be aware of:

  1. If phone goes to sleep your app will no longer execute, so socket will eventually timeout. You can prevent this with wake lock. This will eat devices battery tremendously - I know I wouldn't use that app.
  2. If you do this constantly, even when your app is not active, then you need to use Service.
  3. Activities and Services can be killed off by OS at any time, especially if they are part of an inactive app.

Take a look at AlarmManager, if you need scheduled execution of your code.

Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I usually use getReference method when i do not need to access database state (I mean getter method). Just to change state (I mean setter method). As you should know, getReference returns a proxy object which uses a powerful feature called automatic dirty checking. Suppose the following

public class Person {

    private String name;
    private Integer age;

}


public class PersonServiceImpl implements PersonService {

    public void changeAge(Integer personId, Integer newAge) {
        Person person = em.getReference(Person.class, personId);

        // person is a proxy
        person.setAge(newAge);
    }

}

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

And you know why ???

When you call getReference, you will get a proxy object. Something like this one (JPA provider takes care of implementing this proxy)

public class PersonProxy {

    // JPA provider sets up this field when you call getReference
    private Integer personId;

    private String query = "UPDATE PERSON SET ";

    private boolean stateChanged = false;

    public void setAge(Integer newAge) {
        stateChanged = true;

        query += query + "AGE = " + newAge;
    }

}

So before transaction commit, JPA provider will see stateChanged flag in order to update OR NOT person entity. If no rows is updated after update statement, JPA provider will throw EntityNotFoundException according to JPA specification.

regards,

jQuery vs document.querySelectorAll

as the official site says: "jQuery: The Write Less, Do More, JavaScript Library"

try to translate the following jQuery code without any library

$("p.neat").addClass("ohmy").show("slow");

Invalid character in identifier

Not sure this is right on but when i copied some code form a paper on using pgmpy and pasted it into the editor under Spyder, i kept getting the "invalid character in identifier" error though it didn't look bad to me. The particular line was grade_cpd = TabularCPD(variable='G',\

For no good reason I replaced the ' with " throughout the code and it worked. Not sure why but it did work

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return currentPopulation + currentPopulation * growthRate  / 100;
}

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

Invoking JavaScript code in an iframe from the parent page

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

How to convert a String to JsonObject using gson library

You can convert it to a JavaBean if you want using:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 gson.fromJson(jsonString, JavaBean.class)

To use JsonObject, which is more flexible, use the following:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());

Which is equivalent to the following:

JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();

How to use regex with find command?

find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"

Note that you need to specify .*/ in the beginning because find matches the whole path.

Example:

susam@nifty:~/so$ find . -name "*.jpg"
./foo-111.jpg
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
susam@nifty:~/so$ 
susam@nifty:~/so$ find . -regextype sed -regex ".*/[a-f0-9\-]\{36\}\.jpg"
./test/81397018-b84a-11e0-9d2a-001b77dc0bed.jpg
./81397018-b84a-11e0-9d2a-001b77dc0bed.jpg

My version of find:

$ find --version
find (GNU findutils) 4.4.2
Copyright (C) 2007 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Built using GNU gnulib version e5573b1bad88bfabcda181b9e0125fb0c52b7d3b
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS() CBO(level=0) 
susam@nifty:~/so$ 
susam@nifty:~/so$ find . -regextype foo -regex ".*/[a-f0-9\-]\{36\}\.jpg"
find: Unknown regular expression type `foo'; valid types are `findutils-default', `awk', `egrep', `ed', `emacs', `gnu-awk', `grep', `posix-awk', `posix-basic', `posix-egrep', `posix-extended', `posix-minimal-basic', `sed'.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Just had this problem (again!) after getting a new Lion box.

Best solution I've found (still not 100% optimal, but working):

you can get it by downloading XCode/Dev Tools from Apple - this is a big download -

... but instead I recommend this github which has what you need (and does not have XCode): https://github.com/kennethreitz/osx-gcc-installer

I downloaded their prebuilt PKG for lion, https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg

  • make sure you have downloaded a 64-BIT version of MYSQL Community. (The DMG install is an easy route) http://dev.mysql.com/downloads/mysql/

  • Set paths as follows:

    export PATH=$PATH:/usr/local/mysql-XXXX

    export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

    export ARCHFLAGS='-arch x86_64'

NOTE THAT:

1 in mysql-XXXX above, XXX is the specific version you downloaded. (Probably /usr/local/mysql/ would also work since this is most likely an alias to the same, but I won't pretend to know your setup)

2 I have seen it suggested that ARCHFLAGS be set to '-arch i386 -arch x86_64' but specifying only x86_64 seemed to work better for me. (I can think of some reasons for this but they are not strictly relevant).

  • Install the beast!

    easy_install MySQL-python

  • LAST STEP:

Permanently add the DYLD_LIBRARY_PATH!

You can add it to your bash_profile or similar. This was the missing step for me, without which my system continued to insist on various errors finding _mysql.so and so on.

export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

@richard-boardman, just noticed your soft link solution, which may in effect be doing the same thing my PATH solution does...folks, whatever works best for you.

Best reference: http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

Variable number of arguments in C++?

A C++17 solution: full type safety + nice calling syntax

Since the introduction of variadic templates in C++11 and fold expressions in C++17, it is possible to define a template-function which, at the caller site, is callable as if it was a varidic function but with the advantages to:

  • be strongly type safe;
  • work without the run-time information of the number of arguments, or without the usage of a "stop" argument.

Here is an example for mixed argument types

template<class... Args>
void print(Args... args)
{
    (std::cout << ... << args) << "\n";
}
print(1, ':', " Hello", ',', " ", "World!");

And another with enforced type match for all arguments:

#include <type_traits> // enable_if, conjuction

template<class Head, class... Tail>
using are_same = std::conjunction<std::is_same<Head, Tail>...>;

template<class Head, class... Tail, class = std::enable_if_t<are_same<Head, Tail...>::value, void>>
void print_same_type(Head head, Tail... tail)
{
    std::cout << head;
    (std::cout << ... << tail) << "\n";
}
print_same_type("2: ", "Hello, ", "World!");   // OK
print_same_type(3, ": ", "Hello, ", "World!"); // no matching function for call to 'print_same_type(int, const char [3], const char [8], const char [7])'
                                               // print_same_type(3, ": ", "Hello, ", "World!");
                                                                                              ^

More information:

  1. Variadic templates, also known as parameter pack Parameter pack(since C++11) - cppreference.com.
  2. Fold expressions fold expression(since C++17) - cppreference.com.
  3. See a full program demonstration on coliru.

What are Bearer Tokens and token_type in OAuth 2?

From RFC 6750, Section 1.2:

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

See also: Mozilla MDN Header Information.

How to convert timestamp to datetime in MySQL?

DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`

This is the ultimate solution if the given date is in encoded format like 1300464000

Hash function for a string

Use boost::hash

#include <boost\functional\hash.hpp>

...

std::string a = "ABCDE";
size_t b = boost::hash_value(a);

How to register multiple servlets in web.xml in one Spring application

Use config something like this:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

Find element's index in pandas Series

I'm impressed with all the answers here. This is not a new answer, just an attempt to summarize the timings of all these methods. I considered the case of a series with 25 elements and assumed the general case where the index could contain any values and you want the index value corresponding to the search value which is towards the end of the series.

Here are the speed tests on a 2013 MacBook Pro in Python 3.7 with Pandas version 0.25.3.

In [1]: import pandas as pd                                                

In [2]: import numpy as np                                                 

In [3]: data = [406400, 203200, 101600,  76100,  50800,  25400,  19050,  12700, 
   ...:          9500,   6700,   4750,   3350,   2360,   1700,   1180,    850, 
   ...:           600,    425,    300,    212,    150,    106,     75,     53, 
   ...:            38]                                                                               

In [4]: myseries = pd.Series(data, index=range(1,26))                                                

In [5]: myseries[21]                                                                                 
Out[5]: 150

In [7]: %timeit myseries[myseries == 150].index[0]                                                   
416 µs ± 5.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [8]: %timeit myseries[myseries == 150].first_valid_index()                                        
585 µs ± 32.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [9]: %timeit myseries.where(myseries == 150).first_valid_index()                                  
652 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [10]: %timeit myseries.index[np.where(myseries == 150)[0][0]]                                     
195 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [11]: %timeit pd.Series(myseries.index, index=myseries)[150]                 
178 µs ± 9.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [12]: %timeit myseries.index[pd.Index(myseries).get_loc(150)]                                    
77.4 µs ± 1.41 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [13]: %timeit myseries.index[list(myseries).index(150)]
12.7 µs ± 42.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [14]: %timeit myseries.index[myseries.tolist().index(150)]                   
9.46 µs ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

@Jeff's answer seems to be the fastest - although it doesn't handle duplicates.

Correction: Sorry, I missed one, @Alex Spangher's solution using the list index method is by far the fastest.

Update: Added @EliadL's answer.

Hope this helps.

Amazing that such a simple operation requires such convoluted solutions and many are so slow. Over half a millisecond in some cases to find a value in a series of 25.

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Turning off eslint rule for a specific file

As of today, the answer does not work for me, but putting this at the top of the file does work:

/* eslint-disable @typescript-eslint/no-unused-vars */

It is important to know that at least in my case, the type of comment makes a difference. The previous comment works for me, but the following won't work:

// eslint-disable @typescript-eslint/no-unused-vars

Base64 encoding and decoding in client-side Javascript

In Gecko/WebKit-based browsers (Firefox, Chrome and Safari) and Opera, you can use btoa() and atob().

Original answer: How can you encode a string to Base64 in JavaScript?

What is the default stack size, can it grow, how does it work with garbage collection?

As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.

To answer your specific questions:

  • See this question on how to increase the stack size.
  • You can limit the stack growth by:
    • grouping many local variables in an object: that object will be stored in the heap and only the reference is stored on the stack
    • limit the number of nested function calls (typically by not using recursion)
  • For windows, the default stack size is 320k for 32bit and 1024k for 64bit, see this link.

Form inline inside a form horizontal in twitter bootstrap?

For bootstrap 3 example above works but is overcomplicated, rather than using form-group use form-inline for the fields you want inline.

Eg:

<div class="form-group">
     <label>CVV</label>
     <input type="text" size="4" class="form-control" />
</div>

<div class="form-inline">
      <label>Expiration (MM/YYYY)</label><br>
      <input type="text" size="2" class="form-control" /> / <input type="text" size="4" class="form-control" />
</div>

Nuget connection attempt failed "Unable to load the service index for source"

I have resolved this issue using below steps

  1. Click on run search this %APPDATA%\NuGet\NuGet.config.

  2. Open the setting and add this http_proxy keyin NuGet.config.

  3. Then you will able install the BouncyCastle.Crypto.dll in your application.

Thank you! Responses are welcome if you help this answer.

How to hide axes and gridlines in Matplotlib (python)

# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])

Note, you need matplotlib>=1.2 for set_zticks() to work.

Numpy how to iterate over columns of array?

For example you want to find a mean of each column in matrix. Let's create the following matrix

mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)

The function for mean is

def my_mean(x):
    return sum(x)/len(x)

To do what is needed and store result in colon vector 'results'

results = np.zeros(4)
for i in range(0, 4):
    mat2[:, i] = my_mean(mat2[:, i])

results = mat2[1,:]      

The results are: array([4.33333333, 5. , 5.66666667, 4. ])

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

Can Selenium interact with an existing browser session?

Javascript solution:

I have successfully attached to existing browser session using this function

webdriver.WebDriver.attachToSession(executor, session_id);

Documentation can be found here.

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

Checking if a key exists in a JavaScript object?

New awesome solution with JavaScript Destructuring:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

Do check other use of JavaScript Destructuring

list all files in the folder and also sub folders

You can return a List instead of an array and things gets much simpler.

    public static List<File> listf(String directoryName) {
        File directory = new File(directoryName);

        List<File> resultList = new ArrayList<File>();

        // get all the files from a directory
        File[] fList = directory.listFiles();
        resultList.addAll(Arrays.asList(fList));
        for (File file : fList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                resultList.addAll(listf(file.getAbsolutePath()));
            }
        }
        //System.out.println(fList);
        return resultList;
    } 

How to check for null/empty/whitespace values with a single test?

Functionally, you should be able to use

SELECT column_name
  FROM table_name
 WHERE TRIM(column_name) IS NULL

The problem there is that an index on COLUMN_NAME would not be used. You would need to have a function-based index on TRIM(column_name) if that is a selective condition.

jQuery - checkbox enable/disable

Change your markup slightly:

_x000D_
_x000D_
$(function() {_x000D_
  enable_cb();_x000D_
  $("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    $("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    $("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

How to exit if a command failed?

If you want that behavior for all commands in your script, just add

  set -e 
  set -o pipefail

at the beginning of the script. This pair of options tell the bash interpreter to exit whenever a command returns with a non-zero exit code.

This does not allow you to print an exit message, though.

Class has been compiled by a more recent version of the Java Environment

This is just a version mismatch. You have compiled your code using java version 9 and your current JRE is version 8. Try upgrading your JRE to 9.

49 = Java 5
50 = Java 6
51 = Java 7
52 = Java 8
53 = Java 9
54 = Java 10
55 = Java 11
56 = Java 12
57 = Java 13
58 = Java 14

How do I add a Fragment to an Activity with a programmatically created content view

This may help you

Defining a Fragment

create xml file for fragment view fragment_abc.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

</LinearLayout>

create fragment ABCFragment.java

import androidx.fragment.app.Fragment;

public class FooFragment extends Fragment {
// The onCreateView method is called when Fragment should create its View object hierarchy,
// either dynamically or via XML layout inflation. 

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle 
savedInstanceState) {
    // Defines the xml file for the fragment
    return inflater.inflate(R.layout.fragment_abc, parent, false);
}

// This event is triggered soon after onCreateView().
// Any view setup should occur here.  E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // Setup any handles to view objects here
    // EditText etFoo = (EditText) view.findViewById(R.id.etFoo);
}
}

Add frameLayout in your activity

<FrameLayout
   android:id="@+id/your_placeholder"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

now in activity, add following method

protected void setFragment() {
    // Begin the transaction
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Replace the contents of the container with the new fragment
    ft.replace(R.id.fragment_container, new ABCFragment());
    // or ft.add(R.id.your_placeholder, new ABCFragment());
    // Complete the changes added above
    ft.commit();
}

reference : https://guides.codepath.com/android/creating-and-using-fragments#defining-a-fragment

Excel VBA App stops spontaneously with message "Code execution has been halted"

Thanks to everyone for their input. This problem got solved by choosing REPAIR in Control Panel. I guess this explicitly re-registers some of Office's native COM components and does stuff that REINSTALL doesn't. I expect the latter just goes through a checklist and sometimes accepts what's there if it's already installed, maybe. I then had a separate issue with registering my own .NET dll for COM interop on the user's machine (despite this also working on other machines) though I think this was my error rather than Microsoft. Thanks again, I really appreciate it.

How to tell whether a point is to the right or left side of a line

Here's a version, again using the cross product logic, written in Clojure.

(defn is-left? [line point]
  (let [[[x1 y1] [x2 y2]] (sort line)
        [x-pt y-pt] point]
    (> (* (- x2 x1) (- y-pt y1)) (* (- y2 y1) (- x-pt x1)))))

Example usage:

(is-left? [[-3 -1] [3 1]] [0 10])
true

Which is to say that the point (0, 10) is to the left of the line determined by (-3, -1) and (3, 1).

NOTE: This implementation solves a problem that none of the others (so far) does! Order matters when giving the points that determine the line. I.e., it's a "directed line", in a certain sense. So with the above code, this invocation also produces the result of true:

(is-left? [[3 1] [-3 -1]] [0 10])
true

That's because of this snippet of code:

(sort line)

Finally, as with the other cross product based solutions, this solution returns a boolean, and does not give a third result for collinearity. But it will give a result that makes sense, e.g.:

(is-left? [[1 1] [3 1]] [10 1])
false

Visual Studio 2017 errors on standard headers

If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.

To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK

From there on you can simply build/debug your solution. Hope it helps

enter image description here

Swift: print() vs println() vs NSLog()

A few differences:

  1. print vs println:

    The print function prints messages in the Xcode console when debugging apps.

    The println is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println, you can now safely replace it with print.

    Back in Swift 1.x, print did not add newline characters at the end of the printed string, whereas println did. But nowadays, print always adds the newline character at the end of the string, and if you don't want it to do that, supply a terminator parameter of "".

  2. NSLog:

    • NSLog adds a timestamp and identifier to the output, whereas print will not;

    • NSLog statements appear in both the device’s console and debugger’s console whereas print only appears in the debugger console.

    • NSLog in iOS 10-13/macOS 10.12-10.x uses printf-style format strings, e.g.

        NSLog("%0.4f", CGFloat.pi)
      

      that will produce:

      2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416

    • NSLog from iOS 14/macOS 11 can use string interpolation. (Then, again, in iOS 14 and macOS 11, we would generally favor Logger over NSLog. See next point.)

    Nowadays, while NSLog still works, we would generally use “unified logging” (see below) rather than NSLog.

  3. Effective iOS 14/macOS 11, we have Logger interface to the “unified logging” system. For an introduction to Logger, see WWDC 2020 Explore logging in Swift.

    • To use Logger, you must import os:

      import os
      
    • Like NSLog, unified logging will output messages to both the Xcode debugging console and the device console, too

    • Create a Logger and log a message to it:

      let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      logger.log("url = \(url)")
      

      When you observe the app via the external Console app, you can filter on the basis of the subsystem and category. It is very useful to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app, or (b) messages from other categories or types.

    • You can specify different types of logging messages, either .info, .debug, .error, .fault, .critical, .notice, .trace, etc.:

      logger.error("web service did not respond \(error.localizedDescription)")
      

      So, if using the external Console app, you can choose to only see messages of certain categories (e.g. only show debugging messages if you choose “Include Debug Messages” on the Console “Action” menu). These settings also dictate many subtle issues details about whether things are logged to disk or not. See WWDC video for more details.

    • By default, non-numeric data is redacted in the logs. In the example where you logged the URL, if the app were invoked from the device itself and you were watching from your macOS Console app, you would see the following in the macOS Console:

      url = <private>

      If you are confident that this message will not include user confidential data and you wanted to see the strings in your macOS console, you would have to do:

      os_log("url = \(url, privacy: .public)")
      
  4. Prior to iOS 14/macOS 11, iOS 10/macOS 10.12 introduced os_log for “unified logging”. For an introduction to unified logging in general, see WWDC 2016 video Unified Logging and Activity Tracing.

    • Import os.log:

      import os.log
      
    • You should define the subsystem and category:

      let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network")
      

      When using os_log, you would use a printf-style pattern rather than string interpolation:

      os_log("url = %@", log: log, url.absoluteString)
      
    • You can specify different types of logging messages, either .info, .debug, .error, .fault (or .default):

      os_log("web service did not respond", type: .error)
      
    • You cannot use string interpolation when using os_log. For example with print and Logger you do:

      logger.log("url = \(url)")
      

      But with os_log, you would have to do:

      os_log("url = %@", url.absoluteString)
      
    • The os_log enforces the same data privacy, but you specify the public visibility in the printf formatter (e.g. %{public}@ rather than %@). E.g., if you wanted to see it from an external device, you'd have to do:

      os_log("url = %{public}@", url.absoluteString)
      
    • You can also use the “Points of Interest” log if you want to watch ranges of activities from Instruments:

      let pointsOfInterest = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)
      

      And start a range with:

      os_signpost(.begin, log: pointsOfInterest, name: "Network request")
      

      And end it with:

      os_signpost(.end, log: pointsOfInterest, name: "Network request")
      

      For more information, see https://stackoverflow.com/a/39416673/1271826.

Bottom line, print is sufficient for simple logging with Xcode, but unified logging (whether Logger or os_log) achieves the same thing but offers far greater capabilities.

The power of unified logging comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle. So, you frequently will want to test on a physical device, running the app from the device itself, not starting the app from Xcode’s debugger. Unified logging lets you still watch your iOS device log statements from the macOS Console app.

How to run a program in Atom Editor?

If you know how to launch your program from the command line then you can run it from the platformio-ide-terminal package's terminal. See platformio-ide-terminal provides an embedded terminal within the Atom text editor. So you can issue commands, including commands to run your Java program, from within it. To install this package you can use APM with the command:

$ apm install platformio-ide-terminal --no-confirm

Alternatively, you can install it from the command palette with:

  • Pressing Ctrl+Shift+P. I am assuming this is the appropriate keyboard shortcut for your platform, as you have dealt ith questions about Ubuntu in the past.
  • Type Install Packages and Themes.
  • Search for the platformio-ide-terminal.
  • Install it.

IIS URL Rewrite and Web.config

1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.

2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):

This rule will do SINGLE EXACT rewrite (internal redirect) /page to /page.html. URL in browser will remain unchanged.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRewrite" stopProcessing="true">
                <match url="^page$" />
                <action type="Rewrite" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page it will check if /page.html exists, and if it does then rewrite occurs):

<system.webServer>
    <rewrite>
        <rules>
            <rule name="DynamicRewrite" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
                </conditions>
                <action type="Rewrite" url="/{R:1}.html" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Java - Writing strings to a CSV file

Basically it's because MS Excel can't decide how to open the file with such content.

When you put ID as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.

To solve the issue, change "ID" to "id" and it should work as expected.

enter image description here

This is weird. But, yeah!

Also trying to minimize file access by using file object less.

I tested and the code below works perfect.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvWriter {
  public static void main(String[] args) {

    try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {

      StringBuilder sb = new StringBuilder();
      sb.append("id,");
      sb.append(',');
      sb.append("Name");
      sb.append('\n');

      sb.append("1");
      sb.append(',');
      sb.append("Prashant Ghimire");
      sb.append('\n');

      writer.write(sb.toString());

      System.out.println("done!");

    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }

  }
}

How do I vertically align text in a paragraph?

In my case margin auto works fine.

p {
    font: 22px/24px Ubuntu;
    margin:auto 0px;
}

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

Confused about stdin, stdout and stderr?

As a complement of the answers above, here is a sum up about Redirections: Redirections cheatsheet

EDIT: This graphic is not entirely correct.

The first example does not use stdin at all, it's passing "hello" as an argument to the echo command.

The graphic also says 2>&1 has the same effect as &> however

ls Documents ABC > dirlist 2>&1
#does not give the same output as 
ls Documents ABC > dirlist &>

This is because &> requires a file to redirect to, and 2>&1 is simply sending stderr into stdout

Soft keyboard open and close listener in an activity in Android

"Jaap van Hengstum"'s answer is working for me, but there is no need to set "android:windowSoftInputMode" as he just said!

I've made it smaller(it now just detects what I want, actually an event on showing and hiding of keyboard):

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
        int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        if(heightDiff <= contentViewTop){
            onHideKeyboard();
        } else {
            onShowKeyboard();
        }
    }
};

private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;

protected void onShowKeyboard() {}
protected void onHideKeyboard() {}

protected void attachKeyboardListeners() {
    if (keyboardListenersAttached) {
        return;
    }

    rootLayout = (ViewGroup) findViewById(R.id.CommentsActivity);
    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

    keyboardListenersAttached = true;
}

@Override
protected void onDestroy() {
    super.onDestroy();

    if (keyboardListenersAttached) {
        rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
    }
}

and just don't forget to add this

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comments);
    attachKeyboardListeners();}

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

Set line spacing

You can also use a unit-less value, which is the number of lines: line-height: 2; is double spaced, line-height: 1.5; is one and a half, etc.

Linux / Bash, using ps -o to get process by specific name?

ps -fC PROCESSNAME

ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.

How to remove .html from URL?

Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*).html\ HTTP/
   RewriteRule .* http://localhost/html/%1 [R=301,L]

   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*)\ HTTP/
   RewriteRule .* %1.html [L]
</IfModule>

How do I append to a table in Lua

You are looking for the insert function, found in the table section of the main library.

foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")

How to pass boolean values to a PowerShell script from a command prompt

I think, best way to use/set boolean value as parameter is to use in your PS script it like this:

Param(
    [Parameter(Mandatory=$false)][ValidateSet("true", "false")][string]$deployApp="false"   
)

$deployAppBool = $false
switch($deployPmCmParse.ToLower()) {
    "true" { $deployAppBool = $true }
    default { $deployAppBool = $false }
}

So now you can use it like this:

.\myApp.ps1 -deployAppBool True
.\myApp.ps1 -deployAppBool TRUE
.\myApp.ps1 -deployAppBool true
.\myApp.ps1 -deployAppBool "true"
.\myApp.ps1 -deployAppBool false
#and etc...

So in arguments from cmd you can pass boolean value as simple string :).

Android button background color

If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property

android:backgroundTint="@android:color/holo_green_light"

Delete worksheet in Excel using VBA

You could use On Error Resume Next then there is no need to loop through all the sheets in the workbook.

With On Error Resume Next the errors are not propagated, but are suppressed instead. So here when the sheets does't exist or when for any reason can't be deleted, nothing happens. It is like when you would say : delete this sheets, and if it fails I don't care. Excel is supposed to find the sheet, you will not do any searching.

Note: When the workbook would contain only those two sheets, then only the first sheet will be deleted.

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

How to make background of table cell transparent

I use the "transparent" keyword and it works perfect!

<style type="text/css">
#img table,tr, td {
    border: 1px solid transparent;
    align="center";
    border-spacing: 25px;
    border-collapse: collapse;
    border-width: 5px;
    padding: 5px;
    padding-left: 50px;
}

AngularJS ngClass conditional

ng-class is a Directive of core AngularJs. In which you can use "String Syntax", "Array Syntax", "Evaluated Expression", " Ternary Operator" and many more options described below:

ngClass Using String Syntax

This is the simplest way to use ngClass. You can just add an Angular variable to ng-class and that is the class that will be used for that element.

<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">

<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!

Demo Example of ngClass Using String Syntax

ngClass Using Array Syntax

This is similar to the string syntax method except you are able to apply multiple classes.

<!-- both input boxes below will be classes for the div -->
<input type="text" ng-model="styleOne">
<input type="text" ng-model="styleTwo">

<!-- this div will take on both classes from above -->
<div ng-class="[styleOne, styleTwo]">Look! I'm Words!

ngClass Using Evaluated Expression

A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won't be applied.

<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?

<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">

Example of ngClass Using Evaluated Expression

ngClass Using Value

This is similar to the evaluated expression method except you just able to compares multiple values with the only variable.

<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>

ngClass Using the Ternary Operator

The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:

ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">

Evaluating First, Last or Specific Number

If you are using the ngRepeat directive and you want to apply classes to the first, last, or a specific number in the list, you can use special properties of ngRepeat. These include $first, $last, $even, $odd, and a few others. Here's an example of how to use these.

<!-- add a class to the first item -->
<ul>
  <li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

<!-- add a class to the last item -->
<ul>
  <li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

<!-- add a class to the even items and a different class to the odd items -->
<ul>
  <li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>

python replace single backslash with double backslash

The backslash indicates a special escape character. Therefore, directory = path_to_directory.replace("\", "\\") would cause Python to think that the first argument to replace didn't end until the starting quotation of the second argument since it understood the ending quotation as an escape character.

directory=path_to_directory.replace("\\","\\\\")

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

I had the same issue, and solved it by adding 'mavenCentral()' to build.gradle(Project)

allprojects {
    repositories {
        ...
        mavenCentral()
    }
}

How to use classes from .jar files?

Let's say we need to use the class Classname that is contained in the jar file org.example.jar

And your source is in the file mysource.java Like this:

import org.example.Classname;

public class mysource {
    public static void main(String[] argv) {
    ......
   }
}

First, as you see, in your code you have to import the classes. To do that you need import org.example.Classname;

Second, when you compile the source, you have to reference the jar file.

Please note the difference in using : and ; while compiling

  • If you are under a unix like operating system:

    javac -cp '.:org.example.jar' mysource.java
    
  • If you are under windows:

    javac -cp .;org.example.jar mysource.java
    

After this, you obtain the bytecode file mysource.class

Now you can run this :

  • If you are under a unix like operating system:

    java -cp '.:org.example.jar' mysource
    
  • If you are under windows:

    java -cp .;org.example.jar mysource
    

NoSql vs Relational database

The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.

Using switch statement with a range of value in each case?

You could use an enum to represent your ranges,

public static enum IntRange {
  ONE_TO_FIVE, SIX_TO_TEN;
  public boolean isInRange(int v) {
    switch (this) {
    case ONE_TO_FIVE:
      return (v >= 1 && v <= 5);
    case SIX_TO_TEN:
      return (v >= 6 && v <= 10);
    }
    return false;
  }

  public static IntRange getValue(int v) {
    if (v >= 1 && v <= 5) {
      return ONE_TO_FIVE;
    } else if (v >= 6 && v <= 10) {
      return SIX_TO_TEN;
    }
    return null;
  }
}

How to Batch Rename Files in a macOS Terminal?

I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:

for f in *; do mv "$f" "`echo $f | tr '-' '_'`"; done

Merging two arrays in .NET

I think you can use Array.Copy for this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.

How can Bash execute a command in a different directory context?

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

(cd wherever; mycommand ...)

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

UICollectionView spacing margins

In Objective-C

CGFloat spacing = 5;
UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout*)_habbitCollectionV.collectionViewLayout;
flow.sectionInset = UIEdgeInsetsMake(0, spacing, 0, spacing);
CGFloat itemsPerRow = 2;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat oneMore = itemsPerRow + 1;
CGFloat width = screenRect.size.width - spacing * oneMore;
CGFloat height = width / itemsPerRow;

flow.itemSize = CGSizeMake(floor(height), height);
flow.minimumInteritemSpacing = spacing;
flow.minimumLineSpacing = spacing;

All you have to do is change the itemsPerRow value and it will update the number of items per row accordingly. Furthermore, you can change the spacing value if you want more or less general spacing.

enter image description here enter image description here

How to fix '.' is not an internal or external command error

This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.' and the slash '/'.

Instead of writing:

D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"

Write:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

Initialize 2D array

Easy to read/type.

  table = new char[][] {
      "0123456789".toCharArray()
    , "abcdefghij".toCharArray()
  };

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

For me an update solved the problem:

On Ubuntu:

sudo apt-get update
sudo apt-get upgrade

On CentOS:

sudo yum update

In Tkinter is there any way to make a widget not visible?

You may be interested by the pack_forget and grid_forget methods of a widget. In the following example, the button disappear when clicked

from Tkinter import *

def hide_me(event):
    event.widget.pack_forget()

root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

Change content of div - jQuery

$('a').click(function(){
 $('#content-container').html('My content here :-)');
});

"unary operator expected" error in Bash if condition

You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.

It goes by this syntax: ${VARIABLE:-default}.

The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.

If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

Mobile Redirect using htaccess

Similarly, if you wanted to redirect to a sub-folder instead of a sub-domain, do the following:

Working off of Kevin's great solution you can add this to the .htaccess file in your site's root directory:

    <IfModule mod_rewrite.c>
        RewriteBase /
        RewriteEngine On

        # Check if mobile=1 is set and set cookie 'mobile' equal to 1
        RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
        RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

        # Check if mobile=0 is set and set cookie 'mobile' equal to 0
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

        # cookie can't be set and read in the same request so check
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [S=1]

        # Check if this looks like a mobile device
        RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
        RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
        RewriteCond %{HTTP:Profile}       !^$

        # Check if we're not already on the mobile site
        RewriteCond %{HTTP_HOST}          !^m\.
        # Check to make sure we haven't set the cookie before
        RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
        # Now redirect to the mobile site
        RewriteRule ^ http://www.mysite.com/m/ [R]
    </IfModule>

Then, in the /m/ folder, add or create an .htaccess with the following:

    #Begin user agent loop fix

         RewriteEngine Off
         RewriteBase /

    #End user agent loop fix 

I know it's not a direct answer to the question, but somebody (like me) might stumble upon this question and wonder how that method would be accomplished as well.

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove table row after clicking table row delete button

As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.

This is how we can implement it using jQuery click event instead of using JavaScript onclick.

HTML:

<table id="myTable">
<tr>
  <th width="30%" style="color:red;">ID</th>
  <th width="25%" style="color:red;">Name</th>
  <th width="25%" style="color:red;">Age</th>
  <th width="1%"></th>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-001</td>
  <td width="25%" style="color:red;">Ben</td>
  <td width="25%" style="color:red;">25</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-002</td>
  <td width="25%" style="color:red;">Anderson</td>
  <td width="25%" style="color:red;">47</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-003</td>
  <td width="25%" style="color:red;">Rocky</td>
  <td width="25%" style="color:red;">32</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>

<tr>
  <td width="30%" style="color:red;">SSS-004</td>
  <td width="25%" style="color:red;">Lee</td>
  <td width="25%" style="color:red;">15</td>
  <td><button type='button' class='btnDelete'>x</button></td>
</tr>
                            

jQuery

 $(document).ready(function(){
     $("#myTable").on('click','.btnDelete',function(){
         $(this).closest('tr').remove();
      });
  });

Try in JSFiddle: click here.

How can I kill all sessions connecting to my oracle database?

I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html

select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;

Then ran:

Alter System Kill Session '<value from ss above>'
;

To kill individual sessions.

Side-by-side plots with ggplot2

Using the patchwork package, you can simply use + operator:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))


p1 + p2

patchwork

Other operators include / to stack plots to place plots side by side, and () to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p. For more examples, see the package documentation.

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

How to write UPDATE SQL with Table alias in SQL Server 2008?

The syntax for using an alias in an update statement on SQL Server is as follows:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

Oracle database: How to read a BLOB?

If the content is not too large, you can also use

SELECT CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) FROM <table>;

or

SELECT DUMP ( CAST ( <blobfield> AS RAW( <maxFieldLength> ) ) ) FROM <table>;

This will show you the HEX values.

How to autosize a textarea using Prototype?

For those that are coding for IE and encounter this problem. IE has a little trick that makes it 100% CSS.

<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>

You can even provide a value for rows="n" which IE will ignore, but other browsers will use. I really hate coding that implements IE hacks, but this one is very helpful. It is possible that it only works in Quirks mode.

Newtonsoft JSON Deserialize

As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

var definition = new { Name = "" };

string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);

Console.WriteLine(customer1.Name);
// James

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

What is Mocking?

If your mock involves a network request, another alternative is to have a real test server to hit. You can use a service to generate a request and response for your testing.

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

SHA-1 fingerprint of keystore certificate

If you are using android studio use simple steps:

  • Run your project

  • Click on Gradle menu

  • Expand Gradle task tree

  • Click on android-> signingReport

enter image description here If there is nothing displayed(android studio 2.2) then

Click on Toggle tasks execution/text mode from Run bar

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

How do I center an SVG in a div?

Above answers did not work for me. Adding the attribute preserveAspectRatio="xMidYMin" to the <svg> tag did the trick though. The viewBox attribute needs to be specified for this to work as well. Source: Mozilla developer network

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
else 
    echo "good job for nothing"; 
fi;

that way I resolved my problem. Hope that will help for you too.

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

http://patelshailesh.com/index.php/update-web-config-programmatically

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

What is the difference between varchar and varchar2 in Oracle?

After some experimentation (see below), I can confirm that as of September 2017, nothing has changed with regards to the functionality described in the accepted answer:-

  1. Rextester demo for Oracle 11g: Empty strings are inserted as NULLs for both VARCHAR and VARCHAR2.
  2. LiveSQL demo for Oracle 12c: Same results.

The historical reason for these two keywords is explained well in an answer to a different question.

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Use this:

$root = 'REST_SERVICE_URL'
$user = "user"
$pass= "password"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)

$result = Invoke-RestMethod $root -Credential $credential

How do I enable --enable-soap in php on linux?

In case that you have Ubuntu in your machine, the following steps will help you:

  1. Check first in your php testing file if you have soap (client / server)or not by using phpinfo(); and check results in the browser. In case that you have it, it will seems like the following image ( If not go to step 2 ):

enter image description here

  1. Open your terminal and paste: sudo apt-get install php-soap.

  2. Restart your apache2 server in terminal : service apache2 restart.

  3. To check use your php test file again to be seems like mine in step 1.

How to get the error message from the error code returned by GetLastError()?

MSDN has some sample code that demonstrates how to use FormatMessage() and GetLastError() together: Retrieving the Last-Error Code

Setting background colour of Android layout element

You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

Laravel - htmlspecialchars() expects parameter 1 to be string, object given.

thank me latter.........................

when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error

->use any think who convert array into string it work.

solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}

implode is best way to do it and its 100% work.

Is there any way to change input type="date" format?

I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.

Get the first key name of a JavaScript object

In Javascript you can do the following:

Object.keys(ahash)[0];

How to set my phpmyadmin user session to not time out so quickly?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where <your_new_timeout> is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Convert generic list to dataset in C#

One option would be to use a System.ComponenetModel.BindingList rather than a list.

This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.

What is a 'NoneType' object?

For the sake of defensive programming, objects should be checked against nullity before using.

if obj is None:

or

if obj is not None:

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.

From the Oracle 10g SQL Reference:

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

  • Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
  • The view must not contain any of the following constructs:
    • A set operator
    • a DISTINCT operator
    • An aggregate or analytic function
    • A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
    • A collection expression in a SELECT list
    • A subquery in a SELECT list
    • A subquery designated WITH READ ONLY
    • Joins, with some exceptions, as documented in Oracle Database Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

  • The DML statement must affect only one table underlying the join.
  • For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
  • For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
  • For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

Rounding a number to the nearest 5 or 10 or X

I slightly updated the function provided by the "community wiki" (the best answer), just to round to the nearest 5 (or anything you like), with this exception : the rounded number will NEVER be superior to the original number.

This is useful in cases when it is needed to say that "a company is alive for 47 years" : I want the web page to display "is alive for more than 45 years", while avoiding lying in stating "is alive for more than 50 years".

So when you feed this function with 47, it will not return 50, but will return 45 instead.

'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)

    '@param         num         Long/Integer/Double     The number to be rounded
    '@param         r           Long                    The rounding value
    '@return        OUT         Long                    The rounded value

    'Example usage :
    '   Round 47 to the nearest 5 : it will return 45
    '   Response.Write RoundToNearestBelow(47, 5)

    Dim OUT : OUT = num

    Dim rounded : rounded = Round((((num)) / r), 0) * r

    if (rounded =< num) then
        OUT = rounded
    else
        OUT = rounded - r
    end if

    'Return
    RoundToNearestOrBelow = OUT

end function 'RoundToNearestOrBelow

HTML input - name vs. id

name is used for form submission in DOM (Document Object Model).

ID is used to unique name of html controls in DOM specially for Javascript & CSS

Ignore .pyc files in git repository

You have probably added them to the repository before putting *.pyc in .gitignore.
First remove them from the repository.

Where can I download an offline installer of Cygwin?

  1. Pick a mirror server closest to you from http://cygwin.com/mirrors.html

    Choose any FTP or HTTP mirror.

  2. Download the whole mirror maintaining exact file tree structure of the cygwin directory in the mirror.

    Edit: How to download the whole mirror?

    wget -m <ftp-mirror-url>
    
  3. Execute setup.exe & choose source as local directory and browse to the release directory.

Now you have the Offline Cygwin Installer.

Update: Use Babun. It's based on cygwin and more user friendly. Get Babun

Auto code completion on Eclipse

Its simple these are the steps: 1. first go to the following settings Window -> Preferences -> Java -> Editor -> content assist -> advanced 2. there will be two boxes having checkboxes. 3. check everthing in there and click apply. 4. now ofcourse when you'll be coding there will be auto code completion feature automatically.

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How can I exclude one word with grep?

If your grep supports Perl regular expression with -P option you can do (if bash; if tcsh you'll need to escape the !):

grep -P '(?!.*unwanted_word)keyword' file

Demo:

$ cat file
foo1
foo2
foo3
foo4
bar
baz

Let us now list all foo except foo3

$ grep -P '(?!.*foo3)foo' file
foo1
foo2
foo4
$ 

Android ListView selected item stay highlighted

I found the proper way. It's very simple. In resource describe following:

android:choiceMode="singleChoice"
android:listSelector="#666666"

(or you may specify a resource link instead of color value)

Programmatical:

listView.setSelector(Drawable selector);
listView.setSelector(int resourceId);
listView.setChoiceMode(int mode);

mode can be one of these: AbsListView.CHOICE_MODE_SINGLE, AbsListView.CHOICE_MODE_MULTIPLE, AbsListView.CHOICE_MODE_NONE (default)

(AbsListView is the abstract ancestor for the ListView class)

P.S. manipulations with onItemClick and changing view background are bankrupt, because a view itself is a temporary object. Hence you must not to track a view.

If our list is long enough, the views associated with scrolled out items will be removed from hierarchy, and will be recreated when those items will shown again (with cached display options, such as background). So, the view we have tracked is now not an actual view of the item, and changing its background does nothing to the actual item view. As a result we have multiple items selected.

Android device does not show up in adb list

I have an Android LG G4 and the only thing that worked for me was to install the Software Update and Repair tool from my device. Steps:

  • Plug device into usb
  • Make sure developer options are enabled and usb debugging is checked (see elsewhere in thread or google for instructions)
  • Select usb connection type "Software installation":

enter image description here

  • An installation wizard should come up on the computer.
  • At some point during the installation you will see on your phone a prompt that asks "Trust this computer?" with an RSA token/fingerprint. After you say yes the device should be recognized by ADB and you can finish the wizard.

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007

Get last field using awk substr

It should be a comment to the basename answer but I haven't enough point.

If you do not use double quotes, basename will not work with path where there is space character:

$ basename /home/foo/bar foo/bar.png
bar

ok with quotes " "

$ basename "/home/foo/bar foo/bar.png"
bar.png

file example

$ cat a
/home/parent/child 1/child 2/child 3/filename1
/home/parent/child 1/child2/filename2
/home/parent/child1/filename3

$ while read b ; do basename "$b" ; done < a
filename1
filename2
filename3

How to debug an apache virtual host configuration?

Here's a command I think could be of some help :

apachectl -t -D DUMP_VHOSTS

You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).

You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Use tnsnames.ora in Oracle SQL Developer

I had the same problem, tnsnames.ora worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.

It turns out that the database was caching backup copies of tnsnames.ora like tnsnames.ora.bk2, tnsnames09042811AM4501.bak, tnsnames.ora.bk etc. These files were not readable by the average user.

I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.

The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.

How can I check the system version of Android?

I can't comment on the answers, but there is a huge mistake in Kaushik's answer: SDK_INT is not the same as system version but actually refers to API Level.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
    //this code will be executed on devices running ICS or later
}

The value Build.VERSION_CODES.ICE_CREAM_SANDWICH equals 14. 14 is the API level of Ice Cream Sandwich, while the system version is 4.0. So if you write 4.0, your code will be executed on all devices starting from Donut, because 4 is the API level of Donut (Build.VERSION_CODES.DONUT equals 4).

if(Build.VERSION.SDK_INT >= 4.0){
    //this code will be executed on devices running on DONUT (NOT ICS) or later
}

This example is a reason why using 'magic number' is a bad habit.

How to display the value of the bar on each bar with pyplot.barh()?

Use plt.text() to put text in the plot.

Example:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

This will show the figure as:

bar chart with values at the top

Is it possible to pass parameters programmatically in a Microsoft Access update query?

I just tested this and it works in Access 2010.

Say you have a SELECT query with parameters:

PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));

You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].

Now you create an UPDATE query based on that query:

UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));

You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].

You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:

Sub paramTest()
    Dim qdf As DAO.QueryDef
    Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
    qdf!startID = 1  ' specify
    qdf!endID = 2    '     parameters
    qdf.Execute
    Set qdf = Nothing
End Sub

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

Declaring an HTMLElement Typescript

Note that const declarations are block-scoped.

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

So the value of definitelyAnElement is not accessible outside of the {}.

(I would have commented above, but I do not have enough Reputation apparently.)

How to copy selected lines to clipboard in vim

set guioptions+=a

will, ... uhmm, in short, whenever you select/yank something put it in the clipboard as well (not Vim's, but the global keyboard of the window system). That way you don't have to think about yanking things into a special register.

CSS: How to change colour of active navigation page menu

I think you are getting confused about what the a:active CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected into your CSS and when you select a link, update the selected menu item with new class e.g.

<div class="menuBar">
    <ul>
        <li class="selected"><a href="index.php">HOME</a></li>
        <li><a href="two.php">PORTFOLIO</a></li>
        ....
    </ul>
</div>

// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; } 
// more general CSS
li.selected a { color: #FF0000; }

You will need to update your template page to take in a selectedPage parameter.

Why both no-cache and no-store should be used in HTTP response?

Note that Internet Explorer from version 5 up to 8 will throw an error when trying to download a file served via https and the server sending Cache-Control: no-cache or Pragma: no-cache headers.

See http://support.microsoft.com/kb/812935/en-us

The use of Cache-Control: no-store and Pragma: private seems to be the closest thing which still works.

I'm getting an error "invalid use of incomplete type 'class map'

I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.

class FooReader {
  public:
     /** Constructor */
     FooReader() : d(new FooReaderPrivate(this)) { }  // will not compile here
     .......
  private:
     FooReaderPrivate* d;
};

====== In a separate file =====
class FooReaderPrivate {
  public:
     FooReaderPrivate(FooReader*) : parent(p) { }
  private:
     FooReader* parent;
};

The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.

Configuring diff tool with .gitconfig

Others have done a 99% answer on this, but there is one step left out. (My answer will be coming from OS X so you will have to change file paths accordingly.)

You make these changes to your ~/.gitconfig:

[diff]
    tool = diffmerge
[difftool "diffmerge"]
    cmd = /Applications/Diffmerge.app/Contents/MacOS/diffmerge $LOCAL $REMOTE

This will fix the diff tool. You can also fix this without editing the ~/.gitconfig directly by entering these commands from the terminal:

git config --global diff.tool diffmerge
git config --global difftool.diffmerge.cmd "/Applications/DiffMerge.appContents/MacOS/diffmerge \$LOCAL \$REMOTE"

The 1% that everyone else failed to mention is when using this you can't just run git diff myfile.txt; you need to run git difftool myfile.txt.

How to sleep for five seconds in a batch file/cmd

PING -n 60 127.0.0.1>nul

in case your LAN adapter is not available.

Null pointer Exception on .setOnClickListener

I too got similar error when i misplaced the code

text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

I got it working on placing the code in right order as shown below

setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
 text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            }
    });

Add Variables to Tuple

In Python 3, you can use * to create a new tuple of elements from the original tuple along with the new element.

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

The byte code is almost the same as tuple1 + ("baz",)

Python 3.7.5 (default, Oct 22 2019, 10:35:10) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     tuple1 = ("foo", "bar")
...     tuple2 = (*tuple1, "baz")
...     return tuple2
... 
>>> def g():
...     tuple1 = ("foo", "bar")
...     tuple2 = tuple1 + ("baz",)
...     return tuple2
... 
>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               3 (('baz',))
              8 BUILD_TUPLE_UNPACK       2
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE
>>> dis(g)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               2 (('baz',))
              8 BINARY_ADD
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE

The only difference is BUILD_TUPLE_UNPACK vs BINARY_ADD. The exact performance depends on the Python interpreter implementation, but it's natural to implement BUILD_TUPLE_UNPACK faster than BINARY_ADD because BINARY_ADD is a polymorphic operator, requiring additional type calculation and implicit conversion.

How To: Execute command line in C#, get STD OUT results

One-liner run command:

new Process() { StartInfo = new ProcessStartInfo("echo", "Hello, World") }.Start();

Read output of command in shortest amount of reable code:

    var cliProcess = new Process() {
        StartInfo = new ProcessStartInfo("echo", "Hello, World") {
            UseShellExecute = false,
            RedirectStandardOutput = true
        }
    };
    cliProcess.Start();
    string cliOut = cliProcess.StandardOutput.ReadToEnd();
    cliProcess.WaitForExit();
    cliProcess.Close();

Given URL is not allowed by the Application configuration

This can be caused by incorrect app-ID

In my ionic sample I had the same issue because I had inserted a different "app-ID" in my ionic app other than the app-ID I received from Facebook developer account.

so we have to carefully insert the relavent appID

Border Height on CSS

.main-box{  
    border: solid 10px;
}
.sub-box{
    border-right: 1px solid;
}

//draws a line on right side of the box. later add a margin-top and margin-bottom. i.e.,

.sub-box{
    border-right: 1px solid;
    margin-top: 10px;;
    margin-bottom: 10px;
}

This might help in drawing a line on the right-side of the box with a gap on top and bottom.

HTTP GET request in JavaScript?

I'm not familiar with Mac OS Dashcode Widgets, but if they let you use JavaScript libraries and support XMLHttpRequests, I'd use jQuery and do something like this:

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});

Is there a way to list open transactions on SQL Server 2000 database?

You can get all the information of active transaction by the help of below query

SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION 
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL

and it will give below similar result enter image description here

and you close that transaction by the help below KILL query by refering session id

KILL 77

Moment JS start and end of given month

your startDate is first-day-of-month, In this case we can use

var endDate = moment(startDate).add(1, 'months').subtract(1, 'days');

Hope this helps!!

flutter corner radius with transparent background

Scaffold(
  appBar: AppBar(
    title: Text('BMI CALCULATOR'),
  ),
  body: Container(
    height: 200,
    width: 170,
    margin: EdgeInsets.all(15),
    decoration: BoxDecoration(
      color: Color(
        0xFF1D1E33,
      ),
      borderRadius: BorderRadius.circular(5),
    ),
  ),
);

Using a different font with twitter bootstrap

The easiest way I've seen is to use Google Fonts.

Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.

Google's link to your font

Then add this to your custom.css:

h1, h2, h3, h4, h5, h6 {
    font-family: 'Your Font' !important;
}
p, div {
    font-family: 'Your Font' !important;
}

or

body {
   font-family: 'Your Font' !important;
}

How to connect Android app to MySQL database?

Android does not support MySQL out of the box. The "normal" way to access your database would be to put a Restful server in front of it and use the HTTPS protocol to connect to the Restful front end.

Have a look at ContentProvider. It is normally used to access a local database (SQLite) but it can be used to get data from any data store.

I do recommend that you look at having a local copy of all/some of your websites data locally, that way your app will still work when the Android device hasn't got a connection. If you go down this route then a service can be used to keep the two databases in sync.

How to split string using delimiter char using T-SQL?

You need a split function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

With your split function, you would then use Cross Apply to get the data:

Select T.Col1, T.Col2
    , Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
    , Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
    Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z

How to display two digits after decimal point in SQL Server

You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.

SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name

How can I convert IPV6 address to IPV4 address?

Here is the code you are looking for in javascript. Well you know you can't convert all of the ipv6 addresses

<script>
function parseIp6(str)
{
  //init
  var ar=new Array;
  for(var i=0;i<8;i++)ar[i]=0;
  //check for trivial IPs
  if(str=="::")return ar;
  //parse
  var sar=str.split(':');
  var slen=sar.length;
  if(slen>8)slen=8;
  var j=0;
  for(var i=0;i<slen;i++){
    //this is a "::", switch to end-run mode
    if(i && sar[i]==""){j=9-slen+i;continue;}
    ar[j]=parseInt("0x0"+sar[i]);
    j++;
  }

  return ar;
}
function ipcnvfrom6(ip6)
{
  var ip6=parseIp6(ip6);
  var ip4=(ip6[6]>>8)+"."+(ip6[6]&0xff)+"."+(ip6[7]>>8)+"."+(ip6[7]&0xff);
  return ip4;
}
alert(ipcnvfrom6("::C0A8:4A07"));
</script>

WAMP won't turn green. And the VCRUNTIME140.dll error

WAMP is not turning GREEN? Don`t panic

First of all check your windows update by searching "Windows Update"

or

Download updates from microsoft windows site (i had windows 7 x64 updated to service pack 1 full) windows 7 Service pack 1 download

Now there are some more downloads that support WAMP for installing time

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=5582 https://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) https://www.microsoft.com/en-us/download/details.aspx?id=8328 https://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages[/b] (Visual C++ 2013) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=52685

VC Packages x64 (Visual C++ 2017)

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Login to Microsoft SQL Server Error: 18456

I have faced this issue.

Please look at the attached image,

Step 1: Go to server property

Step 2: Go to Security

Step 3: Change server authentication as SQL server and WindowsAuthenication mode

and restart your Sql server.

enter image description here

Get only specific attributes with from Laravel Collection

this seems to work, but not sure if it's optimized for performance or not.

$request->user()->get(['id'])->groupBy('id')->keys()->all();

output:

array:2 [
  0 => 4
  1 => 1
]

Why extend the Android Application class?

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.

For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

After this,you can get the username and password in any of the activities like this:

MyApplication mApplication = (MyApplication)getApplicationContext();
String username = mApplication.getUsername();
String password = mApplication.getPassword();

And finally, do remember to use the Application object as a singleton object:

 public class MyApplication extends Application {
    private static MyApplication singleton;

    public MyApplication getInstance(){
        return singleton;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }
}

For more information, please Click Application Class

Common elements comparison between 2 lists

Use a generator:

common = (x for x in list1 if x in list2)

The advantage here is that this will return in constant time (nearly instant) even when using huge lists or other huge iterables.

For example,

list1 =  list(range(0,10000000))
list2=list(range(1000,20000000))
common = (x for x in list1 if x in list2)

All other answers here will take a very long time with these values for list1 and list2.

You can then iterate the answer with

for i in common: print(i)

Or convert it to a list with

list(i)

A column-vector y was passed when a 1d array was expected

I also encountered this situation when I was trying to train a KNN classifier. but it seems that the warning was gone after I changed:
knn.fit(X_train,y_train)
to
knn.fit(X_train, np.ravel(y_train,order='C'))

Ahead of this line I used import numpy as np.

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

run from CMD & %path%=set to mysql/bin

mysql_upgrade -u user -ppassword

How to validate phone number in laravel 5.2?

From Laravel 5.5 on you can use an artisan command to create a new Rule which you can code regarding your requirements to decide whether it passes or fail.

Ej: php artisan make:rule PhoneNumber

Then edit app/Rules/PhoneNumber.php, on method passes

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{

    return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
}

Then, use this Rule as you usually would do with the validation:

use App\Rules\PhoneNumber;

$request->validate([
    'name' => ['required', new PhoneNumber],
]);

docs

Platform.runLater and Task in JavaFX

One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():

In UI thread also known as the JavaFX Application thread:

...    
listView.itemsProperty().bind(myListService.resultProperty());
...

in Service implementation (background worker):

...
Platform.runLater(() -> result.add("Element " + finalI));
...

How to change max_allowed_packet size

in MYSQL 5.7, max_allowed_packet is at most 1G. if you want to set it to 4G, it would failed without error and warning.

Seaborn plots not showing up

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

one time i found this script, this copy folder and files and keep the same structure of the source in the destination, you can make some tries with this.

# Find the source files
$sourceDir="X:\sourceFolder"

# Set the target file
$targetDir="Y:\Destfolder\"
Get-ChildItem $sourceDir -Include *.* -Recurse |  foreach {

    # Remove the original  root folder
    $split = $_.Fullname  -split '\\'
    $DestFile =  $split[1..($split.Length - 1)] -join '\' 

    # Build the new  destination file path
    $DestFile = $targetDir+$DestFile

    # Move-Item won't  create the folder structure so we have to 
    # create a blank file  and then overwrite it
    $null = New-Item -Path  $DestFile -Type File -Force
    Move-Item -Path  $_.FullName -Destination $DestFile -Force
}

C# nullable string error

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

Disable submit button ONLY after submit

Hey this works,

   $(function(){
     $(".submitBtn").click(function () {
       $(".submitBtn").attr("disabled", true);
       $('#yourFormId').submit();
     });
   });

angularjs to output plain text instead of html

Use this function like

 String.prototype.text=function(){
   return this ? String(this).replace(/<[^>]+>/gm, '') : '';
 }

  "<span>My text</span>".text()
  output:
  My text

Fiddle