Programs & Examples On #Sqlite3 ruby

The low level SQLite3 library for Ruby. This should only be used for questions about using the low level interface directly.

Redirect to a page/URL after alert button is pressed

window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location = "index.php";';
echo '</script>';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL (AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.

Let me suggest that you do this another way..

echo '<script type="text/javascript">\n'; 
echo 'alert("review your answer");\n'; 
echo 'document.location.href = "index.php";\n';
echo '</script>\n';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.

Best of luck!

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I have spent lots of time doing this I want to put my django app on my server and when I run python manage.py migrate I met this questions

And!! I set this ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock It worked finally!

json_encode is returning NULL?

For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable on entities.

can you add HTTPS functionality to a python flask web server?

The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.

In place of this:

from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')

I used this, with Python 3.7.5:

import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')

and then supplied the SSL context in the Flask.run call as it said:

app.run(…, ssl_context=context)

(My server.crt file is called fullchain.pem and my server.key is called privkey.pem. These files were supplied to me by my LetsEncrypt Certbot.)

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

How to check Oracle database for long running queries

You can generate an AWR (automatic workload repository) report from the database.

Run from the SQL*Plus command line:

SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql

Read the document related to how to generate & understand an AWR report. It will give a complete view of database performance and resource issues. Once we are familiar with the AWR report it will be helpful to find Top SQL which is consuming resources.

Also, in the 12C EM Express UI we can generate an AWR.

How to add time to DateTime in SQL

Or try an alternate method using Time datatype:

DECLARE @MyTime TIME = '03:30:00', @MyDay DATETIME = CAST(GETDATE() AS DATE)

SELECT @MyDay+@MyTime

"SSL certificate verify failed" using pip to install packages

Thank you for the solution. In my case the file %appdata%\pip\pip.ini was not present. I created it manually with this content:

[global]
trusted-host = pypi.python.org files.pythonhosted.org pypi.org pypi.io

How to use Session attributes in Spring-mvc

The below annotated code would set "value" to "name"

@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";
  }
}

To access the same in JSP use ${sessionScope.name}.

For the @ModelAttribute see this link

How to get the cursor to change to the hand when hovering a <button> tag

 #more {
    background:none;
    border:none;
    color:#FFF;
    font-family:Verdana, Geneva, sans-serif;
    cursor: pointer;
}

How to convert string to double with proper cultureinfo

Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture

TryParse does not allway work as we would expect There are change request in .net in this area:

https://github.com/dotnet/runtime/issues/25868

phpmyadmin.pma_table_uiprefs doesn't exist

You just need to change the table names as per the error in - /etc/phpmyadmin/config.inc.php

$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

to

$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma__table_uiprefs’;

assign the table names accordingly and everything will be fine.

For me,sudo dpkg-reconfigure phpmyadmin caused more trouble when I chose the option to re-install the database

Can't operator == be applied to generic types in C#?

So many answers, and not a single one explains the WHY? (which Giovanni explicitly asked)...

.NET generics do not act like C++ templates. In C++ templates, overload resolution occurs after the actual template parameters are known.

In .NET generics (including C#), overload resolution occurs without knowing the actual generic parameters. The only information the compiler can use to choose the function to call comes from type constraints on the generic parameters.

how to run python files in windows command prompt?

First set path of python https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows

and run python file

python filename.py

command line argument with python

python filename.py command-line argument

Most efficient way to create a zero filled JavaScript array?

function makeArrayOf(value, length) {
  var arr = [], i = length;
  while (i--) {
    arr[i] = value;
  }
  return arr;
}

makeArrayOf(0, 5); // [0, 0, 0, 0, 0]

makeArrayOf('x', 3); // ['x', 'x', 'x']

Note that while is usually more efficient than for-in, forEach, etc.

How can I Remove .DS_Store files from a Git repository?

Combining benzado and webmat's answers, updating with git rm, not failing on files found that aren't in repo, and making it paste-able generically for any user:

# remove any existing files from the repo, skipping over ones not in repo
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
# specify a global exclusion list
git config --global core.excludesfile ~/.gitignore
# adding .DS_Store to that list
echo .DS_Store >> ~/.gitignore

how to overwrite css style

You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.

<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
  width: auto;
  float: none;
}
</style>

make: Nothing to be done for `all'

Sometimes "Nothing to be done for all" error can be caused by spaces before command in makefile rule instead of tab. Please ensure that you use tabs instead of spaces inside of your rules.

all:
<\t>$(CC) $(CFLAGS) ...

instead of

all:
    $(CC) $(CFLAGS) ...

Please see the GNU make manual for the rule syntax description: https://www.gnu.org/software/make/manual/make.html#Rule-Syntax

A weighted version of random.choice

I needed to do something like this really fast really simple, from searching for ideas i finally built this template. The idea is receive the weighted values in a form of a json from the api, which here is simulated by the dict.

Then translate it into a list in which each value repeats proportionally to it's weight, and just use random.choice to select a value from the list.

I tried it running with 10, 100 and 1000 iterations. The distribution seems pretty solid.

def weighted_choice(weighted_dict):
    """Input example: dict(apples=60, oranges=30, pineapples=10)"""
    weight_list = []
    for key in weighted_dict.keys():
        weight_list += [key] * weighted_dict[key]
    return random.choice(weight_list)

How to do a JUnit assert on a message in a logger

What I have done if all I want to do is see that some string was logged (as opposed to verifying exact log statements which is just too brittle) is to redirect StdOut to a buffer, do a contains, then reset StdOut:

PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));

// Do something that logs

assertTrue(buffer.toString().contains(myMessage));
System.setOut(original);

Specifying an Index (Non-Unique Key) Using JPA

EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...

The firstName and lastName fields are indexed, together and individually.

@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"})  // Columns indexed together
public class Employee{
    @Id
    private long id;

    @Index                      // F_NAME column indexed
    @Column(name="F_NAME")
    private String firstName;

    @Index                      // L_NAME column indexed
    @Column(name="L_NAME")
    private String lastName;
    ...
}

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

Recently ran into this issue with importing CoreNFC on older iphones (e.g. iPhone 6) and Xcode (11.3.1). I was able to get it to work by

  1. In your Projects, select the target.
  2. Goto General tab on top.
  3. Under the 'Frameworks, Libraries and Embedded Content' section, add the framework (for me it was CoreNFC). Repeat for other targets.
  4. Click on Build Phases on top and expand 'Link Binary with Libraries'.
  5. Make the troublesome framework optional (from required).

This allowed me to compile for older/newer iPhones without making any code changes. I hope this helps other.

How can I show dots ("...") in a span with hidden overflow?

If you are using text-overflow:ellipsis, the browser will show the contents whatever possible within that container. But if you want to specifiy the number of letters before the dots or strip some contents and add dots, you can use the below function.

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }
 
    return string;
}

call like

add3Dots("Hello World",9);

outputs

Hello Wor...

See it in action here

_x000D_
_x000D_
function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}



console.log(add3Dots("Hello, how are you doing today?", 10));
_x000D_
_x000D_
_x000D_

Equivalent of typedef in C#

C# supports some inherited covariance for event delegates, so a method like this:

void LowestCommonHander( object sender, EventArgs e ) { ... } 

Can be used to subscribe to your event, no explicit cast required

gcInt.MyEvent += LowestCommonHander;

You can even use lambda syntax and the intellisense will all be done for you:

gcInt.MyEvent += (sender, e) =>
{
    e. //you'll get correct intellisense here
};

How can I execute PHP code from the command line?

On the command line:

php -i | grep sourceguardian

If it's there, then you'll get some text. If not, you won't get a thing.

How to change the color of a button?

You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.

XML:

<Button
    android:background="@android:color/white"
    android:textColor="@android:color/black"
/>

You can also use hex values ex.

android:background="@android:color/white"

Coding:

//btn represents your button object

btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,

  1. jquery-1.7.1.min.js
  2. jquery.unobtrusive-ajax.min.js

Only these two are enough for performing Ajax operation.

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

I think jQuery cannot find the element.

First of all find the element

var rowTemplate= document.getElementsByName("rowTemplate");

or

var rowTemplate = document.getElementById("rowTemplate"); 

or

var rowTemplate = $('#rowTemplate');

Then try your code again

rowTemplate.html().replace(....)

how to open a url in python

You have to read the data too.

Check out : http://www.doughellmann.com/PyMOTW/urllib2/ to understand it.

response = urllib2.urlopen(..)
headers = response.info()
data = response.read()

Of course, what you want is to render it in browser and aaronasterling's answer is what you want.

Get all mysql selected rows into an array

  1. Loop through the results and place each one in an array

  2. use mysqli_fetch_all() to get them all at one time

SQL Query to fetch data from the last 30 days?

SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;

Now() returns the current Date and Time.

SQL Server add auto increment primary key to existing table

If the column already exists in your table and it is null, you can update the column with this command (replace id, tablename, and tablekey ):

UPDATE x
SET x.<Id> = x.New_Id
FROM (
  SELECT <Id>, ROW_NUMBER() OVER (ORDER BY <tablekey>) AS New_Id
  FROM <tablename>
  ) x

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

How to stop creating .DS_Store on Mac?

NOTE: "Asepsis is no longer under active development and supported under OS X 10.11 (El Capitan) and later."


Here's a comprehensive review of your options. Asepsis (the second solution mentioned) seems to be what you're looking for, it re-routes .DS_Store creation to a unified cache instead of being located on every folder.

How to set <iframe src="..."> without causing `unsafe value` exception?

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

C# Base64 String to JPEG Image

public Image Base64ToImage(string base64String)
{
   // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);

    return image;
}

How to insert a column in a specific position in oracle without dropping and recreating the table?

In 12c you can make use of the fact that columns which are set from invisible to visible are displayed as the last column of the table: Tips and Tricks: Invisible Columns in Oracle Database 12c

Maybe that is the 'trick' @jeffrey-kemp was talking about in his comment, but the link there does not work anymore.

Example:

ALTER TABLE my_tab ADD (col_3 NUMBER(10));
ALTER TABLE my_tab MODIFY (
  col_1 invisible,
  col_2 invisible
);
ALTER TABLE my_tab MODIFY (
  col_1 visible,
  col_2 visible
);

Now col_3 would be displayed first in a SELECT * FROM my_tab statement.

Note: This does not change the physical order of the columns on disk, but in most cases that is not what you want to do anyway. If you really want to change the physical order, you can use the DBMS_REDEFINITION package.

"Items collection must be empty before using ItemsSource."

I ran into this problem because one level of tag, <ListView.View> to be specirfic, was missing in my XAML.

This code produced this error.

<Grid>
    <ListView Margin="10" Name="lvDataBinding" >
        <GridView>
            <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
            <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
        </GridView>
    </ListView>
</Grid>

The following fixed it

<Grid>
    <ListView Margin="10" Name="lvDataBinding" >
        <ListView.View> <!-- This was missing in top! -->
            <GridView>
                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

Tokenizing strings in C

Do it like this:

char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
    printf("token: %s\n", token);
    token = strtok(NULL, " ");
}

Note: strtok modifies the string its tokenising, so it cannot be a const char*.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

Even better use implicit remoting to use a module from another Machine!

$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM

This will allow you to use the module off a remote PC for as long as the PSSession is connected.

More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx

How to make custom error pages work in ASP.NET MVC 4

I would Recommend to use Global.asax.cs File.

 protected void Application_Error(Object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    if (exception is HttpUnhandledException)
    {
        Server.Transfer("~/Error.aspx");
    }
    if (exception != null)
    {
        Server.Transfer("~/Error.aspx");
    }
    try
    {
        // This is to stop a problem where we were seeing "gibberish" in the
        // chrome and firefox browsers
        HttpApplication app = sender as HttpApplication;
        app.Response.Filter = null;
    }
    catch
    {
    }
}

How to move up a directory with Terminal in OS X

To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

alias ..='cd ..'

and then one would need only to type '..[return]'.

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

MSDocs state this for your scenario:

In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:

  1. Run Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force to install the provider from a computer with an internet connection.

  2. After the install, you can find the provider installed in $env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\> or $env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>.

  3. Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.

  4. Restart PowerShell to auto-load the package provider. Alternatively, run Get-PackageProvider -ListAvailable to list all the package providers available on the computer. Then use Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current Windows PowerShell session.

Should composer.lock be committed to version control?

  1. You shouldn't update your dependencies directly on Production.
  2. You should version control your composer.lock file.
  3. You shouldn't version control your actual dependencies.

1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.

2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.

One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.

This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.

So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.

What if you wanna update? Then in your dev environment run: composer update, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.

3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Escape quote in web.config connection string

Use &quot; instead of " to escape it.

web.config is an XML file so you should use XML escaping.

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

See this forum thread.

Update:

&quot; should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \" and ""?

Update 2:

Try single quotes for the connectionString:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'

Or:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word'

Update 3:

From MSDN (SqlConnection.ConnectionString Property):

To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.

So:

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

The issue is not with web.config, but the format of the connection string. In a connection string, if you have a " in a value (of the key-value pair), you need to enclose the value in '. So, while Password=somepass"word does not work, Password='somepass"word' does.

Ruby: How to post a file via HTTP as multipart/form-data?

Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:

  def upload(photo)
    `curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
  end

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Simple way is just concatenate "" with integer:

int i = 100;

String s = "" + i;

now s will have 100 as string value.

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

MySQL Error 1093 - Can't specify target table for update in FROM clause

DELETE FROM story_category
WHERE category_id NOT IN (
    SELECT cid FROM (
        SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id
    ) AS c
)

How to check variable type at runtime in Go language

The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}. If you use a concrete type it will fail.

An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect package. Chaining TypeOf(x).Kind() together you can get a reflect.Kind value which is a uint type: http://golang.org/pkg/reflect/#Kind

You can then do checks for types outside of a switch block, like so:

import (
    "fmt"
    "reflect"
)

// ....

x := 42
y := float32(43.3)
z := "hello"

xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()

fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)

if xt == reflect.Int {
    println(">> x is int")
}
if yt == reflect.Float32 {
    println(">> y is float32")
}
if zt == reflect.String {
    println(">> z is string")
}

Which prints outs:

reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string

Again, this is probably not the preferred way to do it, but it's good to know alternative options.

Are there any free Xml Diff/Merge tools available?

While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).

Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.

The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.

How to access custom attributes from event object in React?

If anyone is trying to use event.target in React and finding a null value, it is because a SyntheticEvent has replaced the event.target. The SyntheticEvent now holds 'currentTarget', such as in event.currentTarget.getAttribute('data-username').

https://facebook.github.io/react/docs/events.html

It looks like React does this so that it works across more browsers. You can access the old properties through a nativeEvent attribute.

How to make an AJAX call without jQuery?

Old but I will try, maybe someone will find this info useful.

This is the minimal amount of code you need to do a GET request and fetch some JSON formatted data. This is applicable only to modern browsers like latest versions of Chrome, FF, Safari, Opera and Microsoft Edge.

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json'); // by default async 
xhr.responseType = 'json'; // in which format you expect the response to be


xhr.onload = function() {
  if(this.status == 200) {// onload called even on 404 etc so check the status
   console.log(this.response); // No need for JSON.parse()
  }
};

xhr.onerror = function() {
  // error 
};


xhr.send();

Also check out new Fetch API which is a promise-based replacement for XMLHttpRequest API.

Execute command without keeping it in history

echo "discreet";history -d $(history 1)

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Java Date cut off time information

Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

Set width to match constraints in ConstraintLayout

set width or height(what ever u need to match parent ) to 0dp and set margins of left , right, top, bottom to act as match parent

Click button copy to clipboard using jQuery

As of 2020, you should use the Clipboard Api.

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

Here is more info about interacting with the clipboard

Get name of object or class

Get your object's constructor function and then inspect its name property.

myObj.constructor.name

Returns "myClass".

How to log request and response body with Retrofit-Android?

I used setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG")), it helped me.
UPDATE.
You can also try for debug purpose use retrofit.client.Response as response model

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
{
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');
}

//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

How to check if a String is numeric in Java

You can use NumberUtils.isCreatable() from Apache Commons Lang.

Since NumberUtils.isNumber will be deprecated in 4.0, so use NumberUtils.isCreatable() instead.

How can I convert a std::string to int?

What about Boost.Lexical_cast?

Here is their example:

The following example treats command line arguments as a sequence of numeric data:

int main(int argc, char * argv[])
{
    using boost::lexical_cast;
    using boost::bad_lexical_cast;

    std::vector<short> args;

    while(*++argv)
    {
        try
        {
            args.push_back(lexical_cast<short>(*argv));
        }
        catch(bad_lexical_cast &)
        {
            args.push_back(0);
        }
    }
    ...
}

How to import JSON File into a TypeScript file?

As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:

  1. Add those three lines to compilerOptions in your tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
  1. Import your json data:
import myData from '../assets/data/my-data.json';

And that's it. You can now use myDatain your components/services.

Currently running queries in SQL Server

I use the below query

SELECT   SPID       = er.session_id
    ,STATUS         = ses.STATUS
    ,[Login]        = ses.login_name
    ,Host           = ses.host_name
    ,BlkBy          = er.blocking_session_id
    ,DBName         = DB_Name(er.database_id)
    ,CommandType    = er.command
    ,ObjectName     = OBJECT_NAME(st.objectid)
    ,CPUTime        = er.cpu_time
    ,StartTime      = er.start_time
    ,TimeElapsed    = CAST(GETDATE() - er.start_time AS TIME)
    ,SQLStatement   = st.text
FROM    sys.dm_exec_requests er
    OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
    LEFT JOIN sys.dm_exec_sessions ses
    ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
    ON con.session_id = ses.session_id
WHERE   st.text IS NOT NULL

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

Expand a div to fill the remaining width

I wrote a javascript function that I call from jQuery $(document).ready(). This will parse all children of the parent div and only update the right most child.

html

...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....

javascript

$(document).ready(function(){
    stretchDivs();
});

function stretchDivs() {
    // loop thru each <div> that has class='stretch'
    $("div.stretch").each(function(){
        // get the inner width of this <div> that has class='stretch'
        var totalW = parseInt($(this).css("width"));
        // loop thru each child node
        $(this).children().each(function(){
            // subtract the margins, borders and padding
            totalW -= (parseInt($(this).css("margin-left")) 
                     + parseInt($(this).css("border-left-width")) 
                     + parseInt($(this).css("padding-left"))
                     + parseInt($(this).css("margin-right")) 
                     + parseInt($(this).css("border-right-width")) 
                     + parseInt($(this).css("padding-right")));
            // if this is the last child, we can set its width
            if ($(this).is(":last-child")) {
                $(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
            } else {
                // this is not the last child, so subtract its width too
                totalW -= parseInt($(this).css("width"));
            }
        });
    });
}

Get random integer in range (x, y]?

Random generator = new Random(); 
int i = generator.nextInt(10) + 1;

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

Is there such a thing as min-font-size and max-font-size?

Please note that setting font-sizing with px is not recommended due to accessibility concerns:

"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)

A more accessible approach is to set font-size: 100% in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em or rem), for example with a @media query.

(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)

Pass Javascript Array -> PHP

You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

As with many, in my situation I was also getting this because of an error. And sadly I could just read the CSS of the html error page.

The source of my problem was also a rewrite rule on the server. It was rewriting http to https.

Current date without time

String test = DateTime.Now.ToString("dd.MM.yyy");

How do I find out what type each object is in a ArrayList<Object>?

import java.util.ArrayList;

/**
 * @author potter
 *
 */
public class storeAny {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Object> anyTy=new ArrayList<Object>();
        anyTy.add(new Integer(1));
        anyTy.add(new String("Jesus"));
        anyTy.add(new Double(12.88));
        anyTy.add(new Double(12.89));
        anyTy.add(new Double(12.84));
        anyTy.add(new Double(12.82));

        for (Object o : anyTy) {
            if(o instanceof String){
                System.out.println(o.toString());
            } else if(o instanceof Integer) {
                System.out.println(o.toString());   
            } else if(o instanceof Double) {
                System.out.println(o.toString());
            }
        }
    }
}

Storing files in SQL Server

There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.

There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)

The article is definitely worth a read.

Linear Layout and weight in Android

Below are the changes (Marked in BOLD) in your code:

<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

  </LinearLayout>

Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).

Since there are 2 views and you have placed android:layout_weight="1" for both the views, it means it will divide the two views equally in horizontal direction (or by width).

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

Declaring variables inside or outside of a loop

The str variable will be available and reserved some space in memory even after while executed below code.

 String str;
    while(condition){
        str = calculateStr();
        .....
    }

The str variable will not be available and also the memory will be released which was allocated for str variable in below code.

while(condition){
    String str = calculateStr();
    .....
}

If we followed the second one surely this will reduce our system memory and increase performance.

How to link a folder with an existing Heroku app

heroku login 

git init

heroku git:remote -a app-name123

then check the remote repo :

git remote -v

Installing PG gem on OS X - failure to build native extension

easy step

  1. brew install postgresql
  2. gem install pg -v 'your version'

Difference between EXISTS and IN in SQL?

Based on rule optimizer:

  • EXISTS is much faster than IN, when the sub-query results is very large.
  • IN is faster than EXISTS, when the sub-query results is very small.

Based on cost optimizer:

  • There is no difference.

Checking session if empty or not

You should first check if Session["emp_num"] exists in the session.

You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])

SQL Server IF NOT EXISTS Usage?

Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.

set nocount on

create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)

insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)

declare @PersonID int
set @PersonID = 1

IF EXISTS    
    (
    SELECT 1    
    FROM Timesheet_Hours    
    WHERE Posted_Flag = 1    
        AND Staff_Id = @PersonID    
    )    
    BEGIN
        RAISERROR('Timesheets have already been posted!', 16, 1)
        ROLLBACK TRAN
    END
ELSE
    IF NOT EXISTS
        (
        SELECT 1
        FROM Timesheet_Hours
        WHERE Staff_Id = @PersonID
        )
        BEGIN
            RAISERROR('Default list has not been loaded!', 16, 1)
            ROLLBACK TRAN
        END
    ELSE
        print 'No problems here'

drop table Timesheet_Hours

Difference between <? super T> and <? extends T> in Java

Based on Bert F's answer I would like to explain my understanding.

Lets say we have 3 classes as

public class Fruit{}

public class Melon extends Fruit{}

public class WaterMelon extends Melon{}

Here We have

List<? extends Fruit> fruitExtendedList = …

//Says that I can be a list of any object as long as this object extends Fruit.

Ok now lets try to get some value from fruitExtendedList

Fruit fruit = fruitExtendedList.get(position)

//This is valid as it can only return Fruit or its subclass.

Again lets try

Melon melon = fruitExtendedList.get(position)

//This is not valid because fruitExtendedList can be a list of Fruit only, it may not be 
//list of Melon or WaterMelon and in java we cannot assign sub class object to 
//super class object reference without explicitly casting it.

Same is the case for

WaterMelon waterMelon = fruitExtendedList.get(position)

Now lets try to set some object in fruitExtendedList

Adding fruit object

fruitExtendedList.add(new Fruit())

//This in not valid because as we know fruitExtendedList can be a list of any 
//object as long as this object extends Fruit. So what if it was the list of  
//WaterMelon or Melon you cannot add Fruit to the list of WaterMelon or Melon.

Adding Melon object

fruitExtendedList.add(new Melon())

//This would be valid if fruitExtendedList was the list of Fruit but it may 
//not be, as it can also be the list of WaterMelon object. So, we see an invalid 
//condition already.

Finally let try to add WaterMelon object

fruitExtendedList.add(new WaterMelon())

//Ok, we got it now we can finally write to fruitExtendedList as WaterMelon 
//can be added to the list of Fruit or Melon as any superclass reference can point 
//to its subclass object.

But wait what if someone decides to make a new type of Lemon lets say for arguments sake SaltyLemon as

public class SaltyLemon extends Lemon{}

Now fruitExtendedList can be list of Fruit, Melon, WaterMelon or SaltyLemon.

So, our statement

fruitExtendedList.add(new WaterMelon())

is not valid either.

Basically we can say that we cannot write anything to a fruitExtendedList.

This sums up List<? extends Fruit>

Now lets see

List<? super Melon> melonSuperList= …

//Says that I can be a list of anything as long as its object has super class of Melon.

Now lets try to get some value from melonSuperList

Fruit fruit = melonSuperList.get(position)

//This is not valid as melonSuperList can be a list of Object as in java all 
//the object extends from Object class. So, Object can be super class of Melon and 
//melonSuperList can be a list of Object type

Similarly Melon, WaterMelon or any other object cannot be read.

But note that we can read Object type instances

Object myObject = melonSuperList.get(position)

//This is valid because Object cannot have any super class and above statement 
//can return only Fruit, Melon, WaterMelon or Object they all can be referenced by
//Object type reference.

Now, lets try to set some value from melonSuperList.

Adding Object type object

melonSuperList.add(new Object())

//This is not valid as melonSuperList can be a list of Fruit or Melon.
//Note that Melon itself can be considered as super class of Melon.

Adding Fruit type object

melonSuperList.add(new Fruit())

//This is also not valid as melonSuperList can be list of Melon

Adding Melon type object

melonSuperList.add(new Melon())

//This is valid because melonSuperList can be list of Object, Fruit or Melon and in 
//this entire list we can add Melon type object.

Adding WaterMelon type object

melonSuperList.add(new WaterMelon())

//This is also valid because of same reason as adding Melon

To sum it up we can add Melon or its subclass in melonSuperList and read only Object type object.

How do I include a file over 2 directories back?

including over directories can be processed by proxy file

  • root
  • .....|__web
  • .....|.........|_requiredDbSettings.php
  • .....|
  • .....|___db
  • .....|.........|_dbsettings.php
  • .....|
  • .....|_proxy.php

    dbsettings.php:
    $host='localhost';
    $user='username':
    $pass='pass';
    
    proxy.php:
    include_once 'db/dbsettings.php
    
    requiredDbSettings.php:
    include_once './../proxy.php';
    

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

How can INSERT INTO a table 300 times within a loop in SQL?

DECLARE @first AS INT = 1
DECLARE @last AS INT = 300

WHILE(@first <= @last)
BEGIN
    INSERT INTO tblFoo VALUES(@first)
    SET @first += 1
END

Modal width (increase)

In Bootstrap 4 you have to use 'max-width' attribute and then it works perfectly.

<div id="modal_dialog" class="modal fade" tabindex="-1" role="dialog" style="display: none;">
<div class="modal-dialog" style="max-width: 1350px!important;" role="document">
    <div class="modal-content">
        <div class="modal-body">
            Sample text
        </div>
    </div>
</div>

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

There are two options available primarily; in case of imputation or filling of missing values NaN / np.nan with only numerical replacements (across column(s):

df['Amount'].fillna(value=None, method= ,axis=1,) is sufficient:

From the Documentation:

value : scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). (values not in the dict/Series/DataFrame will not be filled). This value cannot be a list.

Which means 'strings' or 'constants' are no longer permissable to be imputed.

For more specialized imputations use SimpleImputer():

from sklearn.impute import SimpleImputer
si = SimpleImputer(strategy='constant', missing_values=np.nan, fill_value='Replacement_Value')
df[['Col-1', 'Col-2']] = si.fit_transform(X=df[['C-1', 'C-2']])

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.

public static void RemoveEverythingButUserInfo()
{
    foreach (String o in HttpContext.Current.Session.Keys)
    {
        if (o != "UserInfoIDontWantToAskForAgain")
            keys.Add(o);
    }
}

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Check for column name in a SqlDataReader object

I wrote for Visual Basic users :

Protected Function HasColumnAndValue(ByRef reader As IDataReader, ByVal columnName As String) As Boolean
    For i As Integer = 0 To reader.FieldCount - 1
        If reader.GetName(i).Equals(columnName) Then
            Return Not IsDBNull(reader(columnName))
        End If
    Next

    Return False
End Function

I think this is more powerful and the usage is :

If HasColumnAndValue(reader, "ID_USER") Then
    Me.UserID = reader.GetDecimal(reader.GetOrdinal("ID_USER")).ToString()
End If

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

How to insert date values into table

date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query

Query -

insert into run(id,name,dob)values(&id,'&name','2018-10-20')

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

Adding to a vector of pair

IMHO, a very nice solution is to use c++11 emplace_back function:

revenue.emplace_back("string", map[i].second);

It just creates a new element in place.

What is Ad Hoc Query?

Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries

How to show code but hide output in RMarkdown?

For completely silencing the output, here what works for me

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({


# Your code here
2 * 2
# etc etc


})})
```

The 5 measures used above are

  1. error = FALSE
  2. warning = FALSE
  3. message = FALSE
  4. invisible()
  5. capture.output()

How to set DOM element as the first child?

var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

AngularJS - Access to child scope

Using $emit and $broadcast, (as mentioned by walv in the comments above)

To fire an event upwards (from child to parent)

$scope.$emit('myTestEvent', 'Data to send');

To fire an event downwards (from parent to child)

$scope.$broadcast('myTestEvent', {
  someProp: 'Sending you some data'
});

and finally to listen

$scope.$on('myTestEvent', function (event, data) {
  console.log(data);
});

For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Enjoy :)

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

Note: Use CSS counters to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.


If the browser supports content and counter,

_x000D_
_x000D_
.foo {_x000D_
  counter-reset: foo;_x000D_
}_x000D_
.foo li {_x000D_
  list-style-type: none;_x000D_
}_x000D_
.foo li::before {_x000D_
  counter-increment: foo;_x000D_
  content: "1." counter(foo) " ";_x000D_
}
_x000D_
<ol class="foo">_x000D_
  <li>uno</li>_x000D_
  <li>dos</li>_x000D_
  <li>tres</li>_x000D_
  <li>cuatro</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Multiple Cursors in Sublime Text 2 Windows

It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:

Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.

If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.

Mouse

Windows/Linux

Building blocks:

  • Positive/negative:
    • Add to selection: Ctrl
    • Subtract from selection: Alt In early builds of v3, this didn't work for linear selection.
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or Shift + Right Click On Linux, middle click pastes instead by default.

Combine as you see fit. For example:

  • Add to selection: Ctrl + Left Click (and optionally drag)
  • Subtract from selection: Alt + Left Click This didn't work in early builds of v3.
  • Add block selection: Ctrl + Shift + Right Click (and drag)
  • Subtract block selection: Alt + Shift + Right Click (and drag)

Mac OS X

Building blocks:

  • Positive/negative:
    • Add to selection: ?
    • Subtract from selection: ?? (only works with block selection in v3; presumably bug)
  • Selection type:
    • Linear selection: Left Click
    • Block selection: Middle Click or ? + Left Click

Combine as you see fit. For example:

  • Add to selection: ? + Left Click (and optionally drag)
  • Subtract from selection: ?? + Left Click (and drag--this combination doesn't work in Sublime Text 3, but supposedly it works in 2)
  • Add block selection: ?? + Left Click (and drag)
  • Subtract block selection: ??? + Left Click (and drag)

Keyboard

Windows

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Ctrl + Alt + Up/Down
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Linux

  • Return to single selection mode: Esc
  • Extend selection upward/downward at all carets: Alt + Up/Down Note that you may be able to hold Ctrl as well to get the same shortcuts as Windows, but Linux tends to use Ctrl + Alt combinations for global shortcuts.
  • Extend selection leftward/rightward at all carets: Shift + Left/Right
  • Move all carets up/down/left/right, and clear selection: Up/Down/Left/Right
  • Undo the last selection motion: Ctrl + U
  • Add next occurrence of selected text to selection: Ctrl + D
  • Add all occurrences of the selected text to the selection: Alt + F3
  • Rotate between occurrences of selected text (single selection): Ctrl + F3 (reverse: Ctrl + Shift + F3)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: Ctrl + Shift + L

Mac OS X

  • Return to single selection mode: ? (that's the Mac symbol for Escape)
  • Extend selection upward/downward at all carets: ^??, ^?? (See note)
  • Extend selection leftward/rightward at all carets: ??/??
  • Move all carets up/down/left/right and clear selection: ?, ?, ?, ?
  • Undo the last selection motion: ?U
  • Add next occurrence of selected text to selection: ?D
  • Add all occurrences of the selected text to the selection: ^?G
  • Rotate between occurrences of selected text (single selection): ??G (reverse: ???G)
  • Turn a single linear selection into a block selection, with a caret at the end of the selected text in each line: ??L

Notes for Mac users

On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:

  1. Open System Preferences.
  2. Select the Shortcuts tab.
  3. Select Mission Control in the left listbox.
  4. Change the keyboard shortcuts for Mission Control and Application windows (or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.

In case you're not familiar with Mac's keyboard symbols:

  • ? is the escape key
  • ^ is the control key
  • ? is the option key
  • ? is the shift key
  • ? is the command key
  • ? et al are the arrow keys, as depicted

AFNetworking Post Request

please try below answer.

+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl 
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     if (!responseObject)
     {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(responseObject);
         return ;
     }
     else if ([responseObject isKindOfClass:[NSDictionary class]]) {
         block(responseObject);
         return ;
     }
 }
      failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
 {
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
     [dict setObject:ServerResponceError forKey:@"error"];
     block(dict);
 }];
}

What is the first character in the sort order used by Windows Explorer?

I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.

The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.

I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.

I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.

?foldername

?foldername

?foldername

Is there a typescript List<> and/or Map<> class/library?

Did they add a runtime List<> and/or Map<> type class to typepad 1.0

No, providing a runtime is not the focus of the TypeScript team.

is there a solid library out there someone wrote that provides this functionality?

I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections

Update

JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts : https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want

How to check if a variable is an integer in JavaScript?

Lodash https://lodash.com/docs#isInteger (since 4.0.0) has function to check if variable is an integer:

_.isInteger(3);
// ? true

_.isInteger(Number.MIN_VALUE);
// ? false

_.isInteger(Infinity);
// ? false

_.isInteger('3');
// ? false

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Routing HTTP Error 404.0 0x80070002

Uncheck this in Windows Explorer.

"Hide file type extensions for known types"

Client on Node.js: Uncaught ReferenceError: require is not defined

This is because require() does not exist in the browser/client-side JavaScript.

Now you're going to have to make some choices about your client-side JavaScript script management.

You have three options:

  1. Use the <script> tag.
  2. Use a CommonJS implementation. It has synchronous dependencies like Node.js
  3. Use an asynchronous module definition (AMD) implementation.

CommonJS client side-implementations include (most of them require a build step before you deploy):

  1. Browserify - You can use most Node.js modules in the browser. This is my personal favorite.
  2. Webpack - Does everything (bundles JavaScript code, CSS, etc.). It was made popular by the surge of React, but it is notorious for its difficult learning curve.
  3. Rollup - a new contender. It leverages ES6 modules and includes tree-shaking abilities (removes unused code).

You can read more about my comparison of Browserify vs (deprecated) Component.

AMD implementations include:

  1. RequireJS - Very popular amongst client-side JavaScript developers. It is not my taste because of its asynchronous nature.

Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.

nvm is not compatible with the npm config "prefix" option:

enter image description hereI had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed

For those try to remove nvm from brew

it may not be enough to just brew uninstall nvm

if you see npm prefix is still /usr/local, run this command

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

Adding 1 hour to time variable

You can try this code:

$time = '10:09';

echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}

SwiftUI - How do I change the background color of a View?

Use Below Code for Navigation Bar Color Customization

struct ContentView: View {

@State var msg = "Hello SwiftUI"
init() {
    UINavigationBar.appearance().backgroundColor = .systemPink

     UINavigationBar.appearance().largeTitleTextAttributes = [
        .foregroundColor: UIColor.white,
               .font : UIFont(name:"Helvetica Neue", size: 40)!]

    // 3.
    UINavigationBar.appearance().titleTextAttributes = [
        .font : UIFont(name: "HelveticaNeue-Thin", size: 20)!]

}
var body: some View {
    NavigationView {
    Text(msg)
        .navigationBarTitle(Text("NAVIGATION BAR"))       
    }
    }
}

enter image description here

Get request URL in JSP which is forwarded by Servlet

None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.

http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

Setting query string using Fetch GET request

encodeQueryString — encode an object as querystring parameters

/**
 * Encode an object as url query string parameters
 * - includes the leading "?" prefix
 * - example input — {key: "value", alpha: "beta"}
 * - example output — output "?key=value&alpha=beta"
 * - returns empty string when given an empty object
 */
function encodeQueryString(params) {
    const keys = Object.keys(params)
    return keys.length
        ? "?" + keys
            .map(key => encodeURIComponent(key)
                + "=" + encodeURIComponent(params[key]))
            .join("&")
        : ""
}

encodeQueryString({key: "value", alpha: "beta"})
 //> "?key=value&alpha=beta"

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Xcode Debugger: view value of variable

Try Run->Show->Expressions

Enter in the name of the array or whatever you're looking for.

Is there a float input type in HTML5?

<input type="number" step="any">

This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.

How to empty the message in a text area with jquery?

for set empty all input such textarea select and input run this code:

$('#message').val('').change();

How do I check if a directory exists? "is_dir", "file_exists" or both?

I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath

Here is an example function:

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (long version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    if($path !== false AND is_dir($path))
    {
        // Return canonicalized absolute pathname
        return $path;
    }

    // Path/folder does not exist
    return false;
}

Short version of the same function

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (sort version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    return ($path !== false AND is_dir($path)) ? $path : false;
}

Output examples

<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input);               // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output);              // bool(false)

/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input);         // string(5) "/home"
var_dump($output);              // string(5) "/home"

/** CASE 3 **/
$input = '/home/..';
var_dump($input);               // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output);              // string(1) "/"

Usage

<?php

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))
{
    die('Folder ' . $path . ' already exist');
}

mkdir($folder);
// Continue do stuff

Visual Studio 2015 is very slow

This may help someone visiting this question.

I had an issue where it was slow only in very large files. When opening braces such as { or after completing a type, such as decimal it would hang.

This was resolved by disabling the "Show a completion list after every character is typed" setting in Options => Text Editor => C# => Intellisense

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I had same issue, was due to multiple copies of ssl.conf In /etc/httpd/conf.d - There should only be one.

C dynamically growing array

There are a couple of options I can think of.

  1. Linked List. You can use a linked list to make a dynamically growing array like thing. But you won't be able to do array[100] without having to walk through 1-99 first. And it might not be that handy for you to use either.
  2. Large array. Simply create an array with more than enough space for everything
  3. Resizing array. Recreate the array once you know the size and/or create a new array every time you run out of space with some margin and copy all the data to the new array.
  4. Linked List Array combination. Simply use an array with a fixed size and once you run out of space, create a new array and link to that (it would be wise to keep track of the array and the link to the next array in a struct).

It is hard to say what option would be best in your situation. Simply creating a large array is ofcourse one of the easiest solutions and shouldn't give you much problems unless it's really large.

How do I make a <div> move up and down when I'm scrolling the page?

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.

if($(window).scrollTop() > Height_of_Header){
    //begin to scroll
    $("#div").css("position","fixed");
    $("#div").css("top",0);
}
else{
    //lock it back into place
    $("#div").css("position","relative");
}

How can I save a screenshot directly to a file in Windows?

As far as I know in XP, yes you must use some other app to actually save it.

Vista comes with the Snipping tool, that simplifies the process a bit!

Could not resolve all dependencies for configuration ':classpath'

The solution is in your build.gradle change this block:

allprojects {
  repositories {
    jcenter()
    google()
  }
}

to google in first position :

allprojects {
  repositories {
    google()
    jcenter()
  }
}

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.

Right-click project in Package explorer Build path -> Add external archives...

Select your ojdbc6.jar archive

Press OK

Or

Go through this link and read and do carefully.

The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.

NPM: npm-cli.js not found when running npm

Solution for me in VS2017 (Under Tools | Options ... )

Under Tools | Options ...

I changed the path to: C:\Program Files\nodejs

How to compare binary files to check if they are the same?

I found Visual Binary Diff was what I was looking for, available on:

  • Ubuntu:

    sudo apt install vbindiff
    
  • Arch Linux:

    sudo pacman -S vbindiff
    
  • Mac OS X via MacPorts:

    port install vbindiff
    
  • Mac OS X via Homebrew:

    brew install vbindiff
    

How to set transparent background for Image Button in code?

simply use this in your imagebutton layout

android:background="@null"

using

 android:background="@android:color/transparent 

or

 btn.setBackgroundColor(Color.TRANSPARENT);

doesn't give perfect transparency

Difference between MEAN.js and MEAN.io

The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.

Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%

generator- angular- fullstack offers 8% that MEANJS.org doesn't

  • 1.9% Client-side end-to-end tests
  • 0.6% factory
  • 0.5% provider
  • 0.4% SASS
  • 0.4% LESS
  • 0.4% Compass
  • 0.4% decorator
  • 0.4% Endpoint subgenerator
  • 0.4% Comments
  • 0.3% FontAwesome
  • 0.3% Run server in debug mode
  • 0.3% Save generator answers to a file
  • 0.2% constant
  • 0.2% Development build script: ...... replace 3rd party deps with CDN versions
  • 0.2% Authentication - Cookie
  • 0.2% Authentication - JSON Web Token (JWT)
  • 0.2% Server-side logging
  • 0.1% Development build script: run tasks in parallel to speed it up
  • 0.1% Development build script: Renames asset files to prevent browser caching
  • 0.1% Development build script: run end to end tests
  • 0.1% Production build script: safe pre-minification
  • 0.1% Production build script: add CSS vendor prefixes
  • 0.1% Heroku deployment automation
  • 0.1% value
  • 0.1% Jade
  • 0.1% Coffeescript
  • 0.1% Serverside authenticated route restriction
  • 0.1% SASS version of Twitter Bootstrap
  • 0.1% Production build script: compress images
  • 0.1% OpenShift deployment automation

MeanJS.org. offers 9% that generator-angular-fullstack doesn't

  • 3.7% Dedicated/searchable user group: response time mostly under a day
  • 0.4% Generate routes
  • 0.4% Authentication - Oauth
  • 0.4% config
  • 0.4% i18n, localization
  • 0.4% Input application profile
  • 0.3% FEATURE (a.k.a. module, entity, crud-mock)
  • 0.3% Menus system
  • 0.3% Options for making subcomponents
  • 0.3% test - client side
  • 0.3% Javascript performance thing
  • 0.3% Production build script: make static pages for SEO
  • 0.2% Quick install?
  • 0.2% Dedicated/searchable user group
  • 0.1% Development build script: reload build file upon change
  • 0.1% Development build script: coffee files compiled to JS
  • 0.1% controller - server side
  • 0.1% model - server side
  • 0.1% route - server side
  • 0.1% test - server side
  • 0.1% Swig
  • 0.1% Safe from IP Spoofing
  • 0.1% Production build script: uglification
  • 0.0% Approach to views: URLs start with "#!"
  • 0.0% Approach to frontend services and ajax calls: uses $resource

Here is the one between MEAN.io and MEAN.js in a more readable format

_x000D_
_x000D_
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using github issues<br>&nbsp;&nbsp;&nbsp;&nbsp;* There's a book about it<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold directives<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Only one module definition per file<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Object-relational mapping<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side validation, server-side example<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client side validation, using Angular 1.3<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS views, Directives start with "data-"<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use ng-init<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, URLs start with '#!'<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, LESS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, SASS<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Mocha<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests, using Protractor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Yeoman<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build configurations file(s)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Azure<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Digital Ocean, screencast of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Input application profile<br>&nbsp;&nbsp;&nbsp;&nbsp;* Quick install?<br>&nbsp;&nbsp;&nbsp;&nbsp;* Options for making subcomponents<br>&nbsp;&nbsp;&nbsp;&nbsp;* config generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* directive generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* filter generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* service (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test - client side<br>&nbsp;&nbsp;&nbsp;&nbsp;* view or view partial generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* model (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test (server side) generator<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, Forgotten Password with Resetting<br>&nbsp;&nbsp;&nbsp;&nbsp;* Chat<br>&nbsp;&nbsp;&nbsp;&nbsp;* CSV processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using Nodemailer<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using its own e-mail implementation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, state-based<br>&nbsp;&nbsp;&nbsp;&nbsp;* Paypal integration<br>&nbsp;&nbsp;&nbsp;&nbsp;* Responsive design<br>&nbsp;&nbsp;&nbsp;&nbsp;* Social connections management page<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Creates a favicon<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Safe from IP Spoofing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authorization, Access Contol List (ACL)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Cookie<br>&nbsp;&nbsp;&nbsp;&nbsp;* Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Sponsoring company<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Docs with flatdoc<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Share code between projects<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module manager<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, Use AMD with Require.js<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using wiredep<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Centralized event handling<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* API introspection report and testing interface, using Swagger<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Scaffolding undo&nbsp;&nbsp;&nbsp;&nbsp;(mean package -d &lt;name&gt;)<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Admin page for users and roles<br>&nbsp;&nbsp;&nbsp;&nbsp;* Content Management System&nbsp;&nbsp;&nbsp;&nbsp;(Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br>&nbsp;&nbsp;&nbsp;&nbsp;* File Upload<br>&nbsp;&nbsp;&nbsp;&nbsp;* i18n, localization<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, submenus<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, actually works with backend API<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, using Elastic Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Instrumentation, server-side<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serverside authenticated route restriction<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth, Link multiple Oauth strategies to one account<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Version Control, using git<br><b>Platforms</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side JS Framework, using AngularJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS, using Express<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Google Groups<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Facebook<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, response time mostly under a day<br>&nbsp;&nbsp;&nbsp;&nbsp;* Example application<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English, using Youtube<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated chatroom<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side, with type subfolders<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold services<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold templates<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate route configuration files for each module<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Modularized Functionality<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* No XHR calls in controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Templates, using Angular directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, example of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing, using ui-router<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, HTML5 Mode<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve status codes only as responses<br>&nbsp;&nbsp;&nbsp;&nbsp;* Accept nested, JSON parameters<br>&nbsp;&nbsp;&nbsp;&nbsp;* Add timer header to requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Support for signed and encrypted cookies<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve URLs based on the route definitions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Can serve headers only<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using JSON<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, JavaScript (server side)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, Swig<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate runtime configuration profiles<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Jasmine<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Karma<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Automated device testing, using Live Reload<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests, using Mocha<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI)<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using npm<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using bower<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using Grunt<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using gulp<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, reload build script file upon change<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, copy assets to build or dist or target folder<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects js references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects css references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, LESS/SASS/etc files are linted, compiled<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking, using jshint or jslint<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, run unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, concatenation (aggregation, globbing, bundling)&nbsp;&nbsp;&nbsp;&nbsp;(If you add debug:true to your config/env/development.js the will not be <br>uglified)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, minification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, safe pre-minification, using ng-annotate<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, uglification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, make static pages for SEO<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator&nbsp;&nbsp;&nbsp;&nbsp;(README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* 404 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* 500 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, register/login/logout<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, is password manager friendly<br>&nbsp;&nbsp;&nbsp;&nbsp;* Front-end CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Read<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Create, Update and Delete<br>&nbsp;&nbsp;&nbsp;&nbsp;* Google Analytics<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync, using socket.io<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing, using lodash<br>&nbsp;&nbsp;&nbsp;&nbsp;* One event-loop thread handles all requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Configurable response caching&nbsp;&nbsp;&nbsp;&nbsp;(Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Clustered HTTP sessions<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript obfuscation<br>&nbsp;&nbsp;&nbsp;&nbsp;* https<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Basic&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Digest&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Token&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br></td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Dilemma: when to use Fragments vs Activities:

Why I prefer Fragment over Activity in ALL CASES.

  • Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.

  • Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.

  • A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).

ClassNotFoundException: org.slf4j.LoggerFactory

For a bit more explanation: keep in mind that the "I" in "api" is interface. The slf4j-api jar only holds the needed interfaces (actually LoggerFactory is an abstract class). You also need the actual implementations (an example of which, as noted above, can be found in slf4j-simple). If you look in the jar, you'll find the required classes under the "org.slf4j.impl" package.

How to inherit constructors?

Yes, you have to copy all 387 constructors. You can do some reuse by redirecting them:

  public Bar(int i): base(i) {}
  public Bar(int i, int j) : base(i, j) {}

but that's the best you can do.

Is there a way to add a gif to a Markdown file?

If you can provide your image in SVG format and if it is an icon and not a photo so it can be animated with SMIL animations, then it would be definitely the superior alternative to gif images (or even other formats).

SVG images, like other image files, could be used with either standard markup or HTML <img> element:

![image description](the_path_to/image.svg)
<img src="the_path_to/image.svg" width="128"/>

How might I find the largest number contained in a JavaScript array?

I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for loop, performing ~30% better than Math.max.apply():

function mymax(a)
{
    var m = -Infinity, i = 0, n = a.length;

    for (; i != n; ++i) {
        if (a[i] > m) {
            m = a[i];
        }
    }

    return m;
}

Benchmark results

Convert String to Double - VB

I simple used Eval(string) and it evaluated as Double.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

PHP Echo text Color

How about writing out some HTML tags and some CSS if you're outputting this to the browser?

echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';

Won't work from console though, only through browser.

What does -> mean in Python function definitions?

These are function annotations covered in PEP 3107. Specifically, the -> marks the return function annotation.

Examples:

>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
...    return 1/2*m*v**2
... 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

Annotations are dictionaries, so you can do this:

>>> '{:,} {}'.format(kinetic_energy(20,3000),
      kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

You can also have a python data structure rather than just a string:

>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
...    pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'

Or, you can use function attributes to validate called values:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try: 
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__   
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)       
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

Prints

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>

Change project name on Android Studio

update July/2017: tested and worked


  1. Open project folder (you could open it through Android Studio itself see this )
  2. now close Android Studio
  3. change the yourOldProjectName.iml to the a new name
  4. rename the parent folder to the same new name.
  5. re-open Android Studio --> File --> Open--> path to your renamed.im

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

sudo ln -s /usr/local/mysql-5.5.25-osx10.6-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

That worked for me. I installed MySQL from a dmg file.

Show only two digit after decimal

I think the best and simplest solution is (KISS):

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

How to use particular CSS styles based on screen size / device

@media queries serve this purpose. Here's an example:

@media only screen and (max-width: 991px) and (min-width: 769px){
 /* CSS that should be displayed if width is equal to or less than 991px and larger 
  than 768px goes here */
}

@media only screen and (max-width: 991px){
 /* CSS that should be displayed if width is equal to or less than 991px goes here */
}

Blade if(isset) is not working Laravel

{{ $usersType or '' }} is working fine. The problem here is your foreach loop:

@foreach( $usersType as $type )
    <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
@endforeach

I suggest you put this in an @if():

@if(isset($usersType))
    @foreach( $usersType as $type )
        <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
    @endforeach
@endif

You can also use @forelse. Simple and easy.

@forelse ($users as $user)
   <li>{{ $user->name }}</li>
@empty
   <p>No users</p>
@endforelse

Batch files - number of command line arguments

If the number of arguments should be an exact number (less or equal to 9), then this is a simple way to check it:

if "%2" == "" goto args_count_wrong
if "%3" == "" goto args_count_ok

:args_count_wrong
echo I need exactly two command line arguments
exit /b 1

:args_count_ok

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

How to compare dates in c#

If you have date in DateTime variable then its a DateTime object and doesn't contain any format. Formatted date are expressed as string when you call DateTime.ToString method and provide format in it.

Lets say you have two DateTime variable, you can use the compare method for comparision,

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Code snippet taken from msdn.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How do I format a String in an email so Outlook will print the line breaks?

Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.

This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.

For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:

Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543

Your Outlook recipient will see the information all smashed together, as follows:

Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543

There doesn't seem to be an easy solution. Alternatives are:

  1. You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
  2. You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
  3. You can give up on using a plain text format, and use an html format.

Control cannot fall through from one case label

You can do more than just fall through in C#, but you must utilize the "dreaded" goto statement. For example:

switch (whatever)
{
  case 2:
    Result.Write( "Subscribe" );
    break;
  case 1:
    Result.Write( "Un" );
    goto case 2;
}

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Add another option, maybe not the most lightweight.

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
_x000D_
_x000D_

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach:

Can't start Tomcat as Windows Service

Solution suggested by Prashant worked fine for me.

Tomcat9 Properties > Configure > Startup > Mode = Java Tomcat9 Properties > Configure > Shutdown > Mode = Java

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Importing a csv into mysql via command line

Most answers missing an important point like if you have created csv file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.

the correct syntax would be

load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'

here the difference is '\r\n' as against simply '\n

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Your json contains an array, but you're trying to parse it as an object. This error occurs because objects must start with {.

You have 2 options:

  1. You can get rid of the ShopContainer class and use Shop[] instead

    ShopContainer response  = restTemplate.getForObject(
        url, ShopContainer.class);
    

    replace with

    Shop[] response  = restTemplate.getForObject(url, Shop[].class);
    

    and then make your desired object from it.

  2. You can change your server to return an object instead of a list

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
    

    replace with

    return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
        new ShopContainer(list));
    

How to implement and do OCR in a C# project?

Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}

Implements vs extends: When to use? What's the difference?

extends is for extending a class.

implements is for implementing an interface

The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
     public void doAction() {
       //specify what must happen
     }

     public String doThis(int number) {
       //specfiy what must happen
     }
 }

now extending a class

 public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

in this case

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2

Also, note that an @Override tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden

I suggest you do some more research on dynamic binding, polymorphism and in general inheritance in Object-oriented programming

UICollectionView Set number of columns

This answer is for swift 3.0 -->

first conform to the protocol :

 UICollectionViewDelegateFlowLayout

then add these methods :

    //this method is for the size of items      
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width/3
        let height : CGFloat = 160.0
        return CGSize(width: width, height: height)
    }
    //these methods are to configure the spacing between items

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0,0,0,0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

Update int column in table with unique incrementing values

Try something like this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:

with toupdate as (
    select p.*,
           (coalesce(max(interfaceid) over (), 0) +
            row_number() over (partition by interfaceId order by (select NULL))
           ) as newInterfaceId
    from prices
   )
update p
    set interfaceId = newInterfaceId
    where interfaceId is NULL

Python Anaconda - How to Safely Uninstall

To uninstall Anaconda Fully from your System :

  1. Open Terminal
  2. rm -rf ~/miniconda
  3. rm -rf ~/.condarc ~/.conda ~/.continuum

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

In my case the error was due to incorrect port number (the error is definitely due to incorrect credentials i.e. host/port/dbname/username/password).

Solution:

  1. right click on WAMP tray;
  2. click (drag your cursor) on MySQL;
  3. see the port number used by MySQL;
  4. add same in your Laravel configuration:
    • .env file;
    • config/database.php.

Clear cache php artisan config:cache

Run migration php artisan migrate

How do I prevent the padding property from changing width or height in CSS?

when I add the padding-left property, the width of the DIV changes to 220px

Yes, that is exactly according to the standards. That's how it's supposed to work.

Let's say I create another DIV named anotherdiv exactly the same as newdiv, and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px. I get the same thing, newdiv's width will be 220px;

No, newdiv will remain 200px wide.

Keylistener in Javascript

Here's an update for modern browsers in 2019

_x000D_
_x000D_
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
  if (e.code === "ArrowUp")        playerSpriteX += 10_x000D_
  else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
  document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
_x000D_
_x000D_


Original answer from 2013

window.onkeyup = function(e) {
   var key = e.keyCode ? e.keyCode : e.which;

   if (key == 38) {
       playerSpriteX += 10;
   }else if (key == 40) {
       playerSpriteX -= 10;
   }
}

FIDDLE

Swift: Sort array of objects alphabetically

In the closure you pass to sort, compare the properties you want to sort by. Like this:

movieArr.sorted { $0.name < $1.name }

or the following in the cases that you want to bypass cases:

movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }

Sidenote: Typically only types start with an uppercase letter; I'd recommend using name and date, not Name and Date.


Example, in a playground:

class Movie {
    let name: String
    var date: Int?

    init(_ name: String) {
        self.name = name
    }
}

var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")

let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies

sortedMovies will be in the order [movieA, movieB, movieC]

Swift5 Update

channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
            let channelName1 = channel1.name
            let channelName2 = channel2.name
            return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)

convert string to specific datetime format?

require 'date'

date = DateTime.parse("2011-05-19 10:30:14")
formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y')

See strftime() for more information about formatting dates.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Escaping special characters in Java Regular Expressions

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}

Linq select object from list depending on objects attribute

if a.Correct is a bool flag for the correct answer then you need.

Answer answer = Answers.Single(a => a.Correct);

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

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

EventListener Enter Key

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

C# How to determine if a number is a multiple of another?

followings programs will execute,"one number is multiple of another" in

#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is  multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

What is the difference between Cygwin and MinGW?

Wikipedia Says:

MinGW forked from version 1.3.3 of Cygwin. Although both Cygwin and MinGW can be used to port UNIX software to Windows, they have different approaches: Cygwin aims to provide a complete POSIX layer that provides emulations of several system calls and libraries that exist on Linux, UNIX, and the BSD variants. The POSIX layer runs on top of Windows, sacrificing performance where necessary for compatibility. Accordingly, this approach requires Windows programs written with Cygwin to run on top of a copylefted compatibility library that must be distributed with the program, along with the program's source code. MinGW aims to provide native functionality and performance via direct Windows API calls. Unlike Cygwin, MinGW does not require a compatibility layer DLL and thus programs do not need to be distributed with source code.

Because MinGW is dependent upon Windows API calls, it cannot provide a full POSIX API; it is unable to compile some UNIX applications that can be compiled with Cygwin. Specifically, this applies to applications that require POSIX functionality like fork(), mmap() or ioctl() and those that expect to be run in a POSIX environment. Applications written using a cross-platform library that has itself been ported to MinGW, such as SDL, wxWidgets, Qt, or GTK+, will usually compile as easily in MinGW as they would in Cygwin.

The combination of MinGW and MSYS provides a small, self-contained environment that can be loaded onto removable media without leaving entries in the registry or files on the computer. Cygwin Portable provides a similar feature. By providing more functionality, Cygwin becomes more complicated to install and maintain.

It is also possible to cross-compile Windows applications with MinGW-GCC under POSIX systems. This means that developers do not need a Windows installation with MSYS to compile software that will run on Windows without Cygwin.

InputStream from a URL

(a) wwww.somewebsite.com/a.txt isn't a 'file URL'. It isn't a URL at all. If you put http:// on the front of it it would be an HTTP URL, which is clearly what you intend here.

(b) FileInputStream is for files, not URLs.

(c) The way to get an input stream from any URL is via URL.openStream(), or URL.getConnection().getInputStream(), which is equivalent but you might have other reasons to get the URLConnection and play with it first.

Percentage Height HTML 5/CSS

I am trying to set a div to a certain percentage height in CSS

Percentage of what?

To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.

So the parent of the div must have an explicit height property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.

If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html> and <body>, have to have height: 100%, so there is a chain of explicit percentage heights down to the div.

(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)

Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh) and viewport width (vw):

div {
    height:100vh; 
}

See here for more info.

Accessing MVC's model property from Javascript

try this: (you missed the single quotes)

var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';

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

To get rid of error:

Type '"text"' is not assignable to type '"json"'.

Use

responseType: 'text' as 'json'

import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
 return this.http
        .post<string>(
            this.baseUrl + '/Tickets/getTicket',
            JSON.stringify(value),
        { headers, responseType: 'text' as 'json' }
        )
        .map(res => {
            return res;
        })
        .catch(this.handleError);

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

How do I implement basic "Long Polling"?

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)

msgsrv.php

<?php
if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");
    die();
}

/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

jQuery.ajax returns 400 Bad Request

Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.

$.ajax({
    type: 'get',

must be met with

app.get('/', function(req, res) {

=============== and for post

$.ajax({
    type: 'post',

must be met with

app.post('/', function(req, res) {

Why can't I change my input value in React even with the onChange listener

You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:

<input type="text" onChange={e => this.setState({ text: e.target.value })}/>

How to cut an entire line in vim and paste it?

Let's say that you wanted to cut the line bbb and paste it under the line ---

Before:

aaa
bbb
---

After:

aaa
---
bbb
  1. Put your cursor on the line bbb
  2. Press d+d
  3. Put your cursor on the line ---
  4. Press p

enter image description here

Javascript .querySelector find <div> by innerTEXT

Google has this as a top result for For those who need to find a node with certain text. By way of update, a nodelist is now iterable in modern browsers without having to convert it to an array.

The solution can use forEach like so.

var elList = document.querySelectorAll(".some .selector");
elList.forEach(function(el) {
    if (el.innerHTML.indexOf("needle") !== -1) {
        // Do what you like with el
        // The needle is case sensitive
    }
});

This worked for me to do a find/replace text inside a nodelist when a normal selector could not choose just one node so I had to filter each node one by one to check it for the needle.

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

After a change of ip in our oracle virtual machine, the listener never worked again. Finally these command solved the problem (where 192.168.10.200 is the new ip)

[oracle@oracle admin]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Tue May 10 12:57:37 2016

Copyright (c) 1982, 2009, Oracle. All rights reserved.

Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options

SQL> alter system set local_listener='(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.10.200)(PORT=1521))' scope=both;

System altered.

SQL> alter system register;

System altered.

SQL> exit

Android: Storing username and password?

The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.

I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

illegal character in path

try

"C:/Program Files (x86)/test software/myapp/demo.exe"