Programs & Examples On #Anythingslider

jQuery slider plugin allowing a large range of elements to be used in a slider from images to HTML and more.

#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)

If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.

  1. SHOW CREATE TABLE alarm; Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
  2. ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
  3. ALTER TABLE `alarm` DROP `server_id`

This will delete the foreign key server from the Alarms table.

MySQL: What's the difference between float and double?

Doubles are just like floats, except for the fact that they are twice as large. This allows for a greater accuracy.

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

How do I declare a namespace in JavaScript?

I use the following syntax for the namespace.

var MYNamespace = MYNamespace|| {};

 MYNamespace.MyFirstClass = function (val) {
        this.value = val;
        this.getValue = function(){
                          return this.value;
                       };
    }

var myFirstInstance = new MYNamespace.MyFirstClass(46);
alert(myFirstInstance.getValue());

jsfiddle: http://jsfiddle.net/rpaul/4dngxwb3/1/

Wait for page load in Selenium

I don't think an implicit wait is what you want. Try this:

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

More information in the documentation

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

input[type='text'], input[type='password']
{
   // my css
}

That is the correct way to do it. Sadly CSS is not a programming language.

Twitter Bootstrap onclick event on buttons-radio

This is a really annoying one. What I ended up using is this:

First, create a group of simple buttons with no data-toggle attribute.

<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

Next, write an event handler that simulates the radio button effect by 'activating' the clicked one and 'deactivating' all other buttons. (EDIT: Integrated Nick's cleaner version from the comments.)

$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});

Return in Scala

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
  if (something)
    "A"
  else
    "B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
  if (something)
    "A"
  else
    "B"

  if (somethingElse)
    1
  else
    2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
  if(somethingFirst) {
    if (something)      // Last expression of `if` returns a String
     "A"
    else
     "B"
  }
  else {
    if (somethingElse)
      1
    else
      2

    "C"                // Last expression of `else` returns a String
  }

}

How to compare objects by multiple fields

Its easy to do using Google's Guava library.

e.g. Objects.equal(name, name2) && Objects.equal(age, age2) && ...

More examples:

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

While using formControl, you have to import ReactiveFormsModule to your imports array.

Example:

import {FormsModule, ReactiveFormsModule} from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule,
  ],
  ...
})
export class AppModule {}

Text Editor For Linux (Besides Vi)?

When I searched for TextMate alternative for Linux, I ended up using Geany. It's not as powerfull, but still nice to work with. Great replacement for Kate.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

How can I parse a YAML file from a Linux shell script?

My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.

I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.

YAML looks like so:

KEY:                value
ANOTHER_KEY:        another_value
OH_MY_SO_MANY_KEYS: yet_another_value
LAST_KEY:           last_value

Output like-a dis:

KEY="value"
ANOTHER_KEY="another_value"
OH_MY_SO_MANY_KEYS="yet_another_value"
LAST_KEY="last_value"

I achieved the output with this line:

sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml > file.sh
  • s/:[^:\/\/]/="/g finds : and replaces it with =", while ignoring :// (for URLs)
  • s/$/"/g appends " to the end of each line
  • s/ *=/=/g removes all spaces before =

Search All Fields In All Tables For A Specific Value (Oracle)

I was having following issues for @Lalit Kumars answer,

ORA-19202: Error occurred in XML processing
ORA-00904: "SUCCESS": invalid identifier
ORA-06512: at "SYS.DBMS_XMLGEN", line 288
ORA-06512: at line 1
19202. 00000 -  "Error occurred in XML processing%s"
*Cause:    An error occurred when processing the XML function
*Action:   Check the given error message and fix the appropriate problem

Solution is:

WITH  char_cols AS
  (SELECT /*+materialize */ table_name, column_name
   FROM   cols
   WHERE  data_type IN ('CHAR', 'VARCHAR2'))
SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
       SUBSTR (table_name, 1, 14) "Table",
       SUBSTR (column_name, 1, 14) "Column"
FROM   char_cols,
       TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select "'
       || column_name
       || '" from "'
       || table_name
       || '" where upper("'
       || column_name
       || '") like upper(''%'
       || :val
       || '%'')' ).extract ('ROWSET/ROW/*') ) ) t
ORDER  BY "Table"
/ 

Using intents to pass data between activities

Pass the data from Activity-1 to AndroidTabRes.. as below:

At sending activity...

Intent intent = new Intent(current.this, AndroidTabRestaurantDescSearchListView.class);
intent.putExtra("keyName","value");
startActivity(intent);

At AndroidTabRes.. activity...

  String data = getIntent().getExtras().getString("keyName");

Thus you can have data at receiving activity from sending activity...

And in your AndroidTabRestaurantDescSearchListView class, do this:

String value= getIntent().getStringExtra("keyName");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);

Then in your RatingDescriptionSearchActivity class, do this:

 String data= getIntent().getStringExtra("keyName");

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I usually use float: left; and add overflow: auto; to solve the collapsing parent problem (as to why this works, overflow: auto will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.

The reason I don't use display: table-cell is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.

The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.

enter image description here

How do I install TensorFlow's tensorboard?

The pip package you are looking for is tensorflow-tensorboard developed by Google.

Arrays.asList() of an array

there are two cause of this exception:

1

Arrays.asList(factors) returns a List<int[]> where factors is an int array

2

you forgot to add the type parameter to:

ArrayList<Integer> f = new ArrayList(Arrays.asList(factors));

with:

ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));  

resulting in a compile-time error:

found   : java.util.List<int[]>
required: java.util.List<java.lang.Integer>

How do I check for vowels in JavaScript?

cycles, arrays, regexp... for what? It can be much quicker :)

function isVowel(char)
{
    return char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u' || false;
}

What is the difference between application server and web server?

The main difference between Web server and application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server side code e.g. JSP, Servlet or EJB.

Which one should i use?
Once you know the difference between web and application server and web containers, it's easy to figure out when to use them. You need a web server like Apache HTTPD if you are serving static web pages. If you have a Java application with just JSP and Servlet to generate dynamic content then you need web containers like Tomcat or Jetty. While, if you have Java EE application using EJB, distributed transaction, messaging and other fancy features than you need a full fledged application server like JBoss, WebSphere or Oracle's WebLogic.

Web container is a part of Web Server and the Web Server is a part of Application Server.

Application Server

Web Server is composed of web container, while Application Server is composed of web container as well as EJB container.

What exactly is LLVM?

The LLVM Compiler Infrastructure is particularly useful for performing optimizations and transformations on code. It also consists of a number of tools serving distinct usages. llvm-prof is a profiling tool that allows you to do profiling of execution in order to identify program hotspots. Opt is an optimization tool that offers various optimization passes (dead code elimination for instance).

Importantly LLVM provides you with the libraries, to write your own Passes. For instance if you require to add a range check on certain arguments that are passed into certain functions of a Program, writing a simple LLVM Pass would suffice.

For more information on writing your own Pass, check this http://llvm.org/docs/WritingAnLLVMPass.html

How do I fetch lines before/after the grep result in bash?

The way to do this is near the top of the man page

grep -i -A 10 'error data'

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

Delaying AngularJS route change until model loaded to prevent flicker

This snippet is dependency injection friendly (I even use it in combination of ngmin and uglify) and it's a more elegant domain driven based solution.

The example below registers a Phone resource and a constant phoneRoutes, which contains all your routing information for that (phone) domain. Something I didn't like in the provided answer was the location of the resolve logic -- the main module should not know anything or be bothered about the way the resource arguments are provided to the controller. This way the logic stays in the same domain.

Note: if you're using ngmin (and if you're not: you should) you only have to write the resolve functions with the DI array convention.

angular.module('myApp').factory('Phone',function ($resource) {
  return $resource('/api/phone/:id', {id: '@id'});
}).constant('phoneRoutes', {
    '/phone': {
      templateUrl: 'app/phone/index.tmpl.html',
      controller: 'PhoneIndexController'
    },
    '/phone/create': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        phone: ['$route', 'Phone', function ($route, Phone) {
          return new Phone();
        }]
      }
    },
    '/phone/edit/:id': {
      templateUrl: 'app/phone/edit.tmpl.html',
      controller: 'PhoneEditController',
      resolve: {
        form: ['$route', 'Phone', function ($route, Phone) {
          return Phone.get({ id: $route.current.params.id }).$promise;
        }]
      }
    }
  });

The next piece is injecting the routing data when the module is in the configure state and applying it to the $routeProvider.

angular.module('myApp').config(function ($routeProvider, 
                                         phoneRoutes, 
                                         /* ... otherRoutes ... */) {

  $routeProvider.when('/', { templateUrl: 'app/main/index.tmpl.html' });

  // Loop through all paths provided by the injected route data.

  angular.forEach(phoneRoutes, function(routeData, path) {
    $routeProvider.when(path, routeData);
  });

  $routeProvider.otherwise({ redirectTo: '/' });

});

Testing the route configuration with this setup is also pretty easy:

describe('phoneRoutes', function() {

  it('should match route configuration', function() {

    module('myApp');

    // Mock the Phone resource
    function PhoneMock() {}
    PhoneMock.get = function() { return {}; };

    module(function($provide) {
      $provide.value('Phone', FormMock);
    });

    inject(function($route, $location, $rootScope, phoneRoutes) {
      angular.forEach(phoneRoutes, function (routeData, path) {

        $location.path(path);
        $rootScope.$digest();

        expect($route.current.templateUrl).toBe(routeData.templateUrl);
        expect($route.current.controller).toBe(routeData.controller);
      });
    });
  });
});

You can see it in full glory in my latest (upcoming) experiment. Although this method works fine for me, I really wonder why the $injector isn't delaying construction of anything when it detects injection of anything that is a promise object; it would make things soooOOOOOooOOOOO much easier.

Edit: used Angular v1.2(rc2)

Java, return if trimmed String in List contains String

You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.

If you are using java8 you can simply trim the String using the single line of the code:

myList = myList.stream().map(String :: trim).collect(Collectors.toList());

The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:

if(myList.contains("A")){
    //true
}else{
    // false
}

How to load local file in sc.textFile, instead of HDFS

You need just to specify the path of the file as "file:///directory/file"

example:

val textFile = sc.textFile("file:///usr/local/spark/README.md")

How do I fix "Expected to return a value at the end of arrow function" warning?

The easiest way only if you don't need return something it'ts just return null

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

htaccess remove index.php from url

I don't have to many bulky code to give out just a little snippet solved the issue for me.

i have https://example.com/entitlements/index.php rather i want anyone that types it to get error on request event if you type https://example.com/entitlements/index you will still get error since there's this word "index" is contained there will always be an error thrown back though the content of index.php will still be displayed properly

cletus post on "https://stackoverflow.com/a/1055655/12192635" which solved it

Edit your .htaccess file with the below to redirect people visiting https://example.com/entitlements/index.php to 404 page

RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]

to redirect people visiting https://example.com/entitlements/index to 404 page

RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]

Not withstanding we have already known that the above code works with already existing codes on stack see where i applied the code above just below the all codes at it end.

# The following will allow you to use URLs such as the following:
#
#   example.com/anything
#   example.com/anything/
#
# Which will actually serve files such as the following:
#
#   example.com/anything.html
#   example.com/anything.php
#
# But *only if they exist*, otherwise it will report the usual 404 error.

Options +FollowSymLinks
RewriteEngine On

# Remove trailing slashes.
# e.g. example.com/foo/ will redirect to example.com/foo
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=permanent,QSA]

# Redirect to HTML if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]

# Redirect to PHP if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]

RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]

RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]

Converting XDocument to XmlDocument and vice versa

For me this single line solution works very well

XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

How to get detailed list of connections to database in sql server 2005?

sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2

SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'

(Adapted from SQL Server: Filter output of sp_who2.)

C++11 reverse range-based for-loop

Does this work for you:

#include <iostream>
#include <list>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator_range.hpp>

int main(int argc, char* argv[]){

  typedef std::list<int> Nums;
  typedef Nums::iterator NumIt;
  typedef boost::range_reverse_iterator<Nums>::type RevNumIt;
  typedef boost::iterator_range<NumIt> irange_1;
  typedef boost::iterator_range<RevNumIt> irange_2;

  Nums n = {1, 2, 3, 4, 5, 6, 7, 8};
  irange_1 r1 = boost::make_iterator_range( boost::begin(n), boost::end(n) );
  irange_2 r2 = boost::make_iterator_range( boost::end(n), boost::begin(n) );


  // prints: 1 2 3 4 5 6 7 8 
  for(auto e : r1)
    std::cout << e << ' ';

  std::cout << std::endl;

  // prints: 8 7 6 5 4 3 2 1
  for(auto e : r2)
    std::cout << e << ' ';

  std::cout << std::endl;

  return 0;
}

How can I find my Apple Developer Team id and Team Agent Apple ID?

You can find your team id here:

https://developer.apple.com/account/#/membership

This will get you to your Membership Details, just scroll down to Team ID

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

For me the problem was very strange.
I have a testng.xml file at the root of my Eclipse project. When I changed the file through Eclipse, it wasn't changing the testng.xml file in my directory.

Turns out it made a copy of the folder into the eclipse workspace..

Hope this helps someone out

How can I get the named parameters from a URL using Flask?

url:

http://0.0.0.0:5000/user/name/

code:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(Edit: removed spaces in format string)

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache' http://www.example.com

This curl command servers in its header request to return non-cached data from the web server.

Best way to check if column returns a null value (from database to .net application)

If we are using EF and reading the database element in while loop then,

   using( var idr = connection, SP.......)
   {
       while(idr.read())
       {
          if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
          //do something
       }
   }

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

Plain Old CLR Object vs Data Transfer Object

POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.

Whether a POCO has behaviour or not it's immaterial.

A DTO may be POCO as may a domain object (which would typically be rich in behaviour).

Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.

In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.

How to remove the last character from a bash grep output

Using sed, if you don't know what the last character actually is:

$ grep company_name file.txt | cut -d '=' -f2 | sed 's/.$//'
"Abc Inc"

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

How to create a popup windows in javafx

You can either create a new Stage, add your controls into it or if you require the POPUP as Dialog box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)

For creating a new Stage, you can use the following snippet

@Override
public void start(final Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Open Dialog");
    btn.setOnAction(
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(primaryStage);
                VBox dialogVbox = new VBox(20);
                dialogVbox.getChildren().add(new Text("This is a Dialog"));
                Scene dialogScene = new Scene(dialogVbox, 300, 200);
                dialog.setScene(dialogScene);
                dialog.show();
            }
         });
    }

If you don't want it to be modal (block other windows), use:

dialog.initModality(Modality.NONE);

Frame Buster Buster ... buster code needed

As of 2015, you should use CSP2's frame-ancestors directive for this. This is implemented via an HTTP response header.

e.g.

Content-Security-Policy: frame-ancestors 'none'

Of course, not many browsers support CSP2 yet so it is wise to include the old X-Frame-Options header:

X-Frame-Options: DENY

I would advise to include both anyway, otherwise your site would continue to be vulnerable to Clickjacking attacks in old browsers, and of course you would get undesirable framing even without malicious intent. Most browsers do update automatically these days, however you still tend to get corporate users being stuck on old versions of Internet Explorer for legacy application compatibility reasons.

How to dynamically insert a <script> tag via jQuery after page load?

This answer is technically similar or equal to what jcoffland answered. I just added a query to detect if a script is already present or not. I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)

if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
    $('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);


    while($row = mysqli_fetch_assoc($result))
    {
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";
    }

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

How to find out what character key is pressed?

"Clear" JavaScript:

_x000D_
_x000D_
function myKeyPress(e){
  var keynum;

  if(window.event) { // IE                  
    keynum = e.keyCode;
  } else if(e.which){ // Netscape/Firefox/Opera                 
    keynum = e.which;
  }

  alert(String.fromCharCode(keynum));
}
_x000D_
<input type="text" onkeypress="return myKeyPress(event)" />
_x000D_
_x000D_
_x000D_

JQuery:

_x000D_
_x000D_
$("input").keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
_x000D_
_x000D_
_x000D_

Which HTML elements can receive focus?

The ally.js accessibility library provides an unofficial, test-based list here:

https://allyjs.io/data-tables/focusable.html

(NB: Their page doesn't say how often tests were performed.)

When tracing out variables in the console, How to create a new line?

You should include it inside quotes '\n', See below,

console.log('roleName = '+roleName+ '\n' + 
             'role_ID = '+role_ID+  '\n' + 
             'modal_ID = '+modal_ID+ '\n' +  
             'related = '+related);

Get element of JS object with an index

myobj.A

------- or ----------

myobj['A']

will get you 'B'

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

CSS scale height to match width - possibly with a formfactor

You can set its before and after to force a constant width-to-height ratio

HTML:

<div class="squared"></div>

CSS:

.squared {
  background: #333;
  width: 300px; 
}
.squared::before {
  content: '';
  padding-top: 100%;
  float: left;
}
.squared::after {
  content: '';
  display: block;
  clear: both;
}

How to implode array with key and value without foreach in PHP

You could use http_build_query, like this:

<?php
  $a=array("item1"=>"object1", "item2"=>"object2");
  echo http_build_query($a,'',', ');
?>

Output:

item1=object1, item2=object2 

Demo

Find files in a folder using Java

Have a look at java.io.File.list() and FilenameFilter.

Iterating each character in a string using Python

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

SyntaxError: Cannot use import statement outside a module

Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

Option 1

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

// package.json
{
  "type": "module"
}

Option 2

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

Understanding "VOLUME" instruction in DockerFile

In short: No, your VOLUME instruction is not correct.

Dockerfile's VOLUME specify one or more volumes given container-side paths. But it does not allow the image author to specify a host path. On the host-side, the volumes are created with a very long ID-like name inside the Docker root. On my machine this is /var/lib/docker/volumes.

Note: Because the autogenerated name is extremely long and makes no sense from a human's perspective, these volumes are often referred to as "unnamed" or "anonymous".

Your example that uses a '.' character will not even run on my machine, no matter if I make the dot the first or second argument. I get this error message:

docker: Error response from daemon: oci runtime error: container_linux.go:265: starting container process caused "process_linux.go:368: container init caused "open /dev/ptmx: no such file or directory"".

I know that what has been said to this point is probably not very valuable to someone trying to understand VOLUME and -v and it certainly does not provide a solution for what you try to accomplish. So, hopefully, the following examples will shed some more light on these issues.

Minitutorial: Specifying volumes

Given this Dockerfile:

FROM openjdk:8u131-jdk-alpine
VOLUME vol1 vol2

(For the outcome of this minitutorial, it makes no difference if we specify vol1 vol2 or /vol1 /vol2 — this is because the default working directory within a Dockerfile is /)

Build it:

docker build -t my-openjdk

Run:

docker run --rm -it my-openjdk

Inside the container, run ls in the command line and you'll notice two directories exist; /vol1 and /vol2.

Running the container also creates two directories, or "volumes", on the host-side.

While having the container running, execute docker volume ls on the host machine and you'll see something like this (I have replaced the middle part of the name with three dots for brevity):

DRIVER    VOLUME NAME
local     c984...e4fc
local     f670...49f0

Back in the container, execute touch /vol1/weird-ass-file (creates a blank file at said location).

This file is now available on the host machine, in one of the unnamed volumes lol. It took me two tries because I first tried the first listed volume, but eventually I did find my file in the second listed volume, using this command on the host machine:

sudo ls /var/lib/docker/volumes/f670...49f0/_data

Similarly, you can try to delete this file on the host and it will be deleted in the container as well.

Note: The _data folder is also referred to as a "mount point".

Exit out from the container and list the volumes on the host. They are gone. We used the --rm flag when running the container and this option effectively wipes out not just the container on exit, but also the volumes.

Run a new container, but specify a volume using -v:

docker run --rm -it -v /vol3 my-openjdk

This adds a third volume and the whole system ends up having three unnamed volumes. The command would have crashed had we specified only -v vol3. The argument must be an absolute path inside the container. On the host-side, the new third volume is anonymous and resides together with the other two volumes in /var/lib/docker/volumes/.

It was stated earlier that the Dockerfile can not map to a host path which sort of pose a problem for us when trying to bring files in from the host to the container during runtime. A different -v syntax solves this problem.

Imagine I have a subfolder in my project directory ./src that I wish to sync to /src inside the container. This command does the trick:

docker run -it -v $(pwd)/src:/src my-openjdk

Both sides of the : character expects an absolute path. Left side being an absolute path on the host machine, right side being an absolute path inside the container. pwd is a command that "print current/working directory". Putting the command in $() takes the command within parenthesis, runs it in a subshell and yields back the absolute path to our project directory.

Putting it all together, assume we have ./src/Hello.java in our project folder on the host machine with the following contents:

public class Hello {
    public static void main(String... ignored) {
        System.out.println("Hello, World!");
    }
}

We build this Dockerfile:

FROM openjdk:8u131-jdk-alpine
WORKDIR /src
ENTRYPOINT javac Hello.java && java Hello

We run this command:

docker run -v $(pwd)/src:/src my-openjdk

This prints "Hello, World!".

The best part is that we're completely free to modify the .java file with a new message for another output on a second run - without having to rebuild the image =)

Final remarks

I am quite new to Docker, and the aforementioned "tutorial" reflects information I gathered from a 3-day command line hackathon. I am almost ashamed I haven't been able to provide links to clear English-like documentation backing up my statements, but I honestly think this is due to a lack of documentation and not personal effort. I do know the examples work as advertised using my current setup which is "Windows 10 -> Vagrant 2.0.0 -> Docker 17.09.0-ce".

The tutorial does not solve the problem "how do we specify the container's path in the Dockerfile and let the run command only specify the host path". There might be a way, I just haven't found it.

Finally, I have a gut feeling that specifying VOLUME in the Dockerfile is not just uncommon, but it's probably a best practice to never use VOLUME. For two reasons. The first reason we have already identified: We can not specify the host path - which is a good thing because Dockerfiles should be very agnostic to the specifics of a host machine. But the second reason is people might forget to use the --rm option when running the container. One might remember to remove the container but forget to remove the volume. Plus, even with the best of human memory, it might be a daunting task to figure out which of all anonymous volumes are safe to remove.

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

Why does adb return offline after the device string?

also make sure adb isn't running in your processes automatically. If it's there right click open file location, figure out what is starting it, kill it with fire. Run the updated adb from an updated android sdk platform tools. This was the issue with mine, hope it helps someone.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

How to remove responsive features in Twitter Bootstrap 3?

You can do that by using the Bootstrap 3 CSS with non-responsive features

https://github.com/bassjobsen/non-responsive-tb3

How do I get the logfile from an Android device?

Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:

try {
    File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
    Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

IE 11 doesn't allow you to override the browser compatibility view setting anymore by sending the header...

<meta http-equiv="X-UA-Compatible" content="IE=edge" />  

It appears the only way to force the browser to not use compatibility view is to have the user disable it in their browser. Ours is an Intranet site, and the default IE option is to use compatibility view for Intranet sites. What a pain!

We were able to prevent the need for the user to change their browser settings for users of IE 9 and 10, but it no longer works in IE 11. Our IE users are switching to Chrome, where this is not a problem, and never has been.

Access mysql remote database from command line

Must check whether incoming access to port 3306 is block or not by the firewall.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..

add new tomcat for each new workspace.

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

How to remove list elements in a for loop in Python?

Iterate through a copy of the list:

>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
    print item
    if item == "b":
        a.remove(item)

a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']

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

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

Write Array to Excel Range

Thanks for the pointers guys - the Value vs Value2 argument got me a different set of search results which helped me realise what the answer is. Incidentally, the Value property is a parametrized property, which must be accessed through an accessor in C#. These are called get_Value and set_Value, and take an optional enum value. If anyone's interested, this explains it nicely.

It's possible to make the assignment via the Value2 property however, which is preferable as the interop documentation recommends against the use use of the get_Value and set_Value methods, for reasons beyond my understanding.

The key seems to be the dimension of the array of objects. For the call to work the array must be declared as two-dimensional, even if you're only assigning one-dimensional data.

I declared my data array as an object[NumberofRows,1] and the assignment call worked.

Can't push image to Amazon ECR - fails with "no basic auth credentials"

On Windows in PowerShell, use:

Invoke-Expression $(aws ecr get-login --no-include-email)

ImportError: DLL load failed: %1 is not a valid Win32 application

I just hit this and the problem was that the package had at one point been installed in the per-user packages directory. (On Windows.) aka %AppData%\Python. So Python was looking there first, finding an old 32-bit version of the .pyd file, and failing with the listed error. Unfortunately pip uninstall by itself wasn't enough to clean this, and at this time pip 10.0.1 doesn't seem to have a --user parameter for uninstall, only for install.

tl;dr Deleting the old .pyd from %AppData%\python\python27\site-packages resolved this problem for me.

Select all occurrences of selected word in VSCode

In my MacOS case for some reason Cmd+Shift+L is not working while pressing the short cut on the keyboard (although it work just fine while clicking on this option in menu: Selection -> Select All Occurences). So for me pressing Cmd+FN+F2 did the trick (FN is for enabling "F2" obviously).

Btw, if you forget this shortcut just do right-click on the selection and see "Change All Occurrences" option

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

To avoid regex hell you could find your first match, chop off a chunk then attempt to find the next one on the substring. In C# this looks something like this, sorry I've not ported it over to JavaScript for you.

        long count = 0;
        var remainder = data;
        Match match = null;
        do
        {
            match = _rgx.Match(remainder);
            if (match.Success)
            {
                count++;
                remainder = remainder.Substring(match.Index + 1, remainder.Length - (match.Index+1));
            }
        } while (match.Success);
        return count;

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>

and js

$(document).ready( function() {
$('#prev').click(function() {
  $.ajax({
  type: 'POST',
  url: 'ajax.php',
  data: 'id=testdata',
  cache: false,
  success: function(data) {
    result=data.split('~');
    $('#content1').html(result[0]);
  },
  });
});
});

How to install 2 Anacondas (Python 2 and 3) on Mac OS

Edit!: Please be sure that you should have both Python installed on your computer.

Maybe my answer is late for you but I can help someone who has the same problem!

You don't have to download both Anaconda.

If you are using Spyder and Jupyter in Anaconda environmen and,

If you have already Anaconda 2 type in Terminal:

    python3 -m pip install ipykernel

    python3 -m ipykernel install --user

If you have already Anaconda 3 then type in terminal:

    python2 -m pip install ipykernel

    python2 -m ipykernel install --user

Then before use Spyder you can choose Python environment like below! Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!

Anaconda spyder Python 2.7 or 3.5

Also this is Jupyter. You can choose python version like this!

Jupyter Notebook

I hope it will help.

Send Mail to multiple Recipients in java

So ... it took many months, but still ... You can send email to multiple recipients by using the ',' as separator and

message.setRecipients(Message.RecipientType.CC, "[email protected],[email protected],[email protected]");

is ok. At least in JavaMail 1.4.5

Get method arguments using Spring AOP?

if your using @Aspect an option is add this method inside your Aspect and send the JoinPoint and the name of parameter you need.

private Object getParameter(ProceedingJoinPoint joinPoint, String parameterName) {
    Object valueParameter = null;
    if (Objects.nonNull(joinPoint) && joinPoint.getSignature() instanceof MethodSignature
            && Objects.nonNull(parameterName) ) {
        MethodSignature method = (MethodSignature)joinPoint.getSignature();
        String[] parameters = method.getParameterNames();
        for (int t = 0; t< parameters.length; t++) {
            if( Objects.nonNull(parameters[t]) && parameters[t].equals(parameterName)) {
                Object[] obj = joinPoint.getArgs();
                valueParameter = obj[t];
            }
        }
    }
    return valueParameter;
}

and the call example:

Object parameterObject = getParameter(joinPoint, "nameClient");
if ( Objects.nonNull(parameterObject) ) {
    String parametro = String.valueOf(parameterObject);
}

Only need know the type of object for convert

Using setDate in PreparedStatement

Not sure, but what I think you're looking for is to create a java.util.Date from a String, then convert that java.util.Date to a java.sql.Date.

try this:

private static java.sql.Date getCurrentDate(String date) {

    java.util.Date today;
    java.sql.Date rv = null;
    try {

        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        today = format.parse(date);
        rv = new java.sql.Date(today.getTime());
        System.out.println(rv.getTime());

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    } finally {
        return rv;
    }

}    

Will return a java.sql.Date object for setDate();

The function above will print out a long value:

1375934400000

How do I change the background color with JavaScript?

Add this script element to your body element, changing the color as desired:

_x000D_
_x000D_
<body>_x000D_
  <p>Hello, World!</p>_x000D_
  <script type="text/javascript">_x000D_
     document.body.style.backgroundColor = "#ff0000";  // red_x000D_
  </script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Remove specific characters from a string in Python

Am I missing the point here, or is it just the following:

string = "ab1cd1ef"
string = string.replace("1","") 

print string
# result: "abcdef"

Put it in a loop:

a = "a!b@c#d$"
b = "!@#$"
for char in b:
    a = a.replace(char,"")

print a
# result: "abcd"

Percentage calculation

(current / maximum) * 100. In your case, (2 / 10) * 100.

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

Insert current date/time using now() in a field using MySQL/PHP

Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:

enter image description here

Now, any new post will automatically get a unique date and time. Hope this can help.

php is null or empty?

This is not a bug but PHP normal behavior. It happens because the == operator in PHP doesn't check for type.

'' == null == 0 == false

If you want also to check if the values have the same type, use === instead. To study in deep this difference, please read the official documentation.

Nginx - Customizing 404 page

Be careful with the syntax! Great Turtle used them interchangeably, but:

error_page 404 = /404.html;

Will return the 404.html page with a status code of 200 (because = has relayed that to this page)

error_page 404 /404.html;

Will return the 404.html page with a (the original) 404 error code.

https://serverfault.com/questions/295789/nginx-return-correct-headers-with-custom-error-documents

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Angular routerLink does not navigate to the corresponding component

There is also another case which suits this situation. If in your interceptor, you made it return non Boolean value, the end result is like that.

For example, I had tried to return obj && obj[key] stuff. After debugging for a while, then I realize I have to convert this to Boolean type manually like Boolean(obj && obj[key]) in order to let the clicking pass.

Reverse colormap in matplotlib

There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:

from matplotlib.colors import Normalize

class InvertedNormalize(Normalize):
    def __call__(self, *args, **kwargs):
        return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)

You can then use this with plot_surface and other Matplotlib plotting functions by doing e.g.

inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)

This will work with any Matplotlib colormap.

How to disable horizontal scrolling of UIScrollView?

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

How do I make case-insensitive queries on Mongodb?

The following query will find the documents with required string insensitively and with global occurrence also

db.collection.find({name:{
                             $regex: new RegExp(thename, "ig")
                         }
                    },function(err, doc) {
                                         //Your code here...
                  });

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

Find out free space on tablespace

Here is a query used by Oracle SQL Developer in its Tablespaces view

select a.tablespace_name as "Tablespace Name",
       round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
       round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
       round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
       100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
       round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from  ( select  f.tablespace_name,
               sum(f.bytes) bytes_alloc,
               sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
        from dba_data_files f
        group by tablespace_name) a,
      ( select  f.tablespace_name,
               sum(f.bytes)  bytes_free
        from dba_free_space f
        group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select 
       h.tablespace_name as tablespace_name,
       round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
       round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
       round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
       round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
       100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
       round(sum(f.maxbytes) / 1048576) max
from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where  p.file_id(+) = h.file_id
and    p.tablespace_name(+) = h.tablespace_name
and    f.file_id = h.file_id
and    f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;

How to add display:inline-block in a jQuery show() function?

<style>
.demo-ele{display:inline-block}
</style>

<div class="demo-ele" style="display:none">...</div>

<script>
$(".demo-ele").show(1000);//hide first, show with inline-block
<script>

Go install fails with error: no install location for directory xxx outside GOPATH

You'll want to have 3 directories inside your chosen GOPATH directory.

GOPATH
     /bin
     /src
       /someProgram
        program.go
       /someLibrary
        library.go
     /pkg

Then you'll run go install from inside either someProgram (which puts an executable in bin) or someLibrary (which puts a library in pkg).

How to use google maps without api key

Hey You can Use this insted

<iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&amp;height=600&amp;hl=en&amp;q=%C4%B0ikaneir+(Mumma's%20Bakery)&amp;ie=UTF8&amp;t=&amp;z=14&amp;iwloc=B&amp;output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>

Creating a byte array from a stream

You can even make it fancier with extensions:

namespace Foo
{
    public static class Extensions
    {
        public static byte[] ToByteArray(this Stream stream)
        {
            using (stream)
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                     stream.CopyTo(memStream);
                     return memStream.ToArray();
                }
            }
        }
    }
}

And then call it as a regular method:

byte[] arr = someStream.ToByteArray()

Finding smallest value in an array most efficiently

If finding the minimum is a one time thing, just iterate through the list and find the minimum.

If finding the minimum is a very common thing and you only need to operate on the minimum, use a Heap data structure.

A heap will be faster than doing a sort on the list but the tradeoff is you can only find the minimum.

How can I make a clickable link in an NSAttributedString?

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:strSomeTextWithLinks];

NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor redColor],   
                                 NSUnderlineColorAttributeName: [UIColor blueColor],
                                 NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

customTextView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;

KEY POINTS:

  • Make sure that you enable "Selectable" behavior of the UITextView in XIB.
  • Make sure that you disable "Editable" behavior of the UITextView in XIB.

How can I print a circular structure in a JSON-like format?

Use the JSON.stringify method with a replacer. Read this documentation for more information. http://msdn.microsoft.com/en-us/library/cc836459%28v=vs.94%29.aspx

var obj = {
  a: "foo",
  b: obj
}

var replacement = {"b":undefined};

alert(JSON.stringify(obj,replacement));

Figure out a way to populate the replacement array with cyclic references. You can use the typeof method to find if an the property is of type 'object' ( reference ) and an exact equality check ( === ) to verify circular reference.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I never managed to get git to work completely in Powershell. But in the git bash shell I did not have any permission related issues, and I did not need to set chmod etc... After adding the ssh to Github I was up and running.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

What is the JavaScript version of sleep()?

I have searched/googled quite a few webpages on javascript sleep/wait... and there is NO answer if you want javascript to "RUN, DELAY, RUN"... what most people got was either, "RUN, RUN(useless stuff), RUN" or "RUN, RUN + delayed RUN"....

So I ate some burgers and got thinking::: here is a solution that works... but you have to chop up your running codes...::: yes, I know, this is just an easier to read refactoring... still...

//......................................... //example1:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setInterval
var i = 0;

function run() {
    //pieces of codes to run
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i >2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" is ran</p>"; }
    if (i==5){document.getElementById("id1").innerHTML= "<p>all code segment finished running</p>"; clearInterval(t); } //end interval, stops run
    i++; //segment of code finished running, next...
}

run();
t=setInterval("run()",1000);

</script>
</body>
</html>

//.................................... //example2:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function run() {
    //pieces of codes to run, can use switch statement
    if (i==0){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(1000);}
    if (i==1){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(2000);}
    if (i==2){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>"; sleep(3000);}
    if (i==3){document.getElementById("id1").innerHTML= "<p>code segment "+ i +" ran</p>";} //stops automatically
    i++;
}

function sleep(dur) {t=setTimeout("run()",dur);} //starts flow control again after dur

run(); //starts
</script>
</body>
</html>

//................. example3:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout
var i = 0;

function flow() {
    run(i);
    i++; //code segment finished running, increment i; can put elsewhere
    sleep(1000);
    if (i==5) {clearTimeout(t);} //stops flow, must be after sleep()
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow
</script>
</body>
</html>

//.............. example4:

<html>
<body>
<div id="id1">DISPLAY</div>

<script>
//javascript sleep by "therealdealsince1982"; copyrighted 2009
//setTimeout, switch
var i = 0;

function flow() {
    switch(i)
    {
        case 0:
            run(i);
            sleep(1000);
            break;
        case 1:
            run(i);
            sleep(2000);
            break;
        case 5:
            run(i);
            clearTimeout(t); //stops flow
            break;
        default:
            run(i);
            sleep(3000);
            break;
    }
}

function run(segment) {
    //pieces of codes to run, can use switch statement
    if (segment==0){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==1){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment==2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    if (segment >2){document.getElementById("id1").innerHTML= "<p>code segment "+ segment +" is ran</p>"; }
    i++; //current segment of code finished running, next...
}

function sleep(dur) {t=setTimeout("flow()",dur);} //starts flow control again after dur

flow(); //starts flow control for first time...
</script>
</body>
</html>

How Many Seconds Between Two Dates?

I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.

var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();

var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);

A handy source for future reference is the MDN site

Alternatively, if your dates come in a format javascript can parse

var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);

and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning)

Setting WPF image source in code

You can also reduce this to one line. This is the code I used to set the Icon for my main window. It assumes the .ico file is marked as Content and is being copied to the output directory.

 this.Icon = new BitmapImage(new Uri("Icon.ico", UriKind.Relative));

View more than one project/solution in Visual Studio

There is a way to store multiple solutions in one instance of VS.

Attempt the following steps:

  1. File > Open > Project/Solution
  2. This will bring up the open project window, notice at the bottom where it says options, select add to solution

Add to Solution

  1. Then select the file you want to add and click open
  2. This will then add the solution to your project. You still won't be able to run the same project in a single instance of VS, but you can have all your code organized in one place.

NOTE: This worked for Visual Studio 2013 Professional

How to order events bound with jQuery

Here's my shot at this, covering different versions of jQuery:

// Binds a jQuery event to elements at the start of the event chain for that type.
jQuery.extend({
    _bindEventHandlerAtStart: function ($elements, eventType, handler) {
        var _data;

        $elements.bind(eventType, handler);
        // This bound the event, naturally, at the end of the event chain. We
        // need it at the start.

        if (typeof jQuery._data === 'function') {
            // Since jQuery 1.8.1, it seems, that the events object isn't
            // available through the public API `.data` method.
            // Using `$._data, where it exists, seems to work.
            _data = true;
        }

        $elements.each(function (index, element) {
            var events;

            if (_data) {
                events = jQuery._data(element, 'events')[eventType];
            } else {
                events = jQuery(element).data('events')[eventType];
            }

            events.unshift(events.pop());

            if (_data) {
                jQuery._data(element, 'events')[eventType] = events;
            } else {
                jQuery(element).data('events')[eventType] = events;
            }
        });
    }
});

Array.push() if does not exist?

Push dynamically

var a = [
  {name:"bull", text: "sour"},
  {name: "tom", text: "tasty" },
  {name: "Jerry", text: "tasty" }
]

function addItem(item) {
  var index = a.findIndex(x => x.name == item.name)
  if (index === -1) {
    a.push(item);
  }else {
    console.log("object already exists")
  }
}

var item = {name:"bull", text: "sour"};
addItem(item);

In simple method

var item = {name:"bull", text: "sour"};
a.findIndex(x => x.name == item.name) == -1 ? a.push(item) : console.log("object already exists")

If the array contains only primitive types/ simple array

var b = [1, 7, 8, 4, 3];
var newItem = 6;
b.indexOf(newItem) === -1 && b.push(newItem);

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Encrypt Password in Configuration Files?

Try using ESAPIs Encryption methods. Its easy to configure and you can also easily change your keys.

http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/Encryptor.html

You

1)encrypt 2)decrypt 3)sign 4)unsign 5)hashing 6)time based signatures and much more with just one library.

How to update only one field using Entity Framework?

You can tell EF which properties have to be updated in this way:

public void ChangePassword(int userId, string password)
{
  var user = new User { Id = userId, Password = password };
  using (var context = new ObjectContext(ConnectionString))
  {
    var users = context.CreateObjectSet<User>();
    users.Attach(user);
    context.ObjectStateManager.GetObjectStateEntry(user)
      .SetModifiedProperty("Password");
    context.SaveChanges();
  }
}

nginx error connect to php5-fpm.sock failed (13: Permission denied)

I just got this error again today as I updated my machine (with updates for PHP) running Ubuntu 14.04. The distribution config file /etc/php5/fpm/pool.d/www.conf is fine and doesn't require any changes currently.

I found the following errors:

dmesg | grep php
[...]
[ 4996.801789] traps: php5-fpm[23231] general protection ip:6c60d1 sp:7fff3f8c68f0 error:0 in php5-fpm[400000+800000]
[ 6788.335355] traps: php5-fpm[9069] general protection ip:6c5d81 sp:7fff98dd9a00 error:0 in php5-fpm[400000+7ff000]

The strange thing was that I have 2 sites running that utilize PHP-FPM on this machine one was running fine and the other (a Tiny Tiny RSS installation) gave me a 502, where both have been running fine before.

I compared both configuration files and found that fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; was missing for the affected site.

Both configuration files now contain the following block and are running fine again:

location ~ \.php$ {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include /etc/nginx/snippets/fastcgi-php.conf;
}

Update

It should be noted that Ubuntu ships two fastcgi related parameter files and also a configuration snippet which is available since Vivid and also in the PPA version. The solution was updated accordingly.

Diff of the fastcgi parameter files:

$ diff -up fastcgi_params fastcgi.conf
--- fastcgi_params      2015-07-22 01:42:39.000000000 +0200
+++ fastcgi.conf        2015-07-22 01:42:39.000000000 +0200
@@ -1,4 +1,5 @@

+fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
 fastcgi_param  QUERY_STRING       $query_string;
 fastcgi_param  REQUEST_METHOD     $request_method;
 fastcgi_param  CONTENT_TYPE       $content_type;

Configuration snippet in /etc/nginx/snippets/fastcgi-php.conf

# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

How to populate options of h:selectOneMenu from database?

I'm doing it like this:

  1. Models are ViewScoped

  2. converter:

    @Named
    @ViewScoped
    public class ViewScopedFacesConverter implements Converter, Serializable
    {
            private static final long serialVersionUID = 1L;
            private Map<String, Object> converterMap;
    
            @PostConstruct
            void postConstruct(){
                converterMap = new HashMap<>();
            }
    
            @Override
            public String getAsString(FacesContext context, UIComponent component, Object object) {
                String selectItemValue = String.valueOf( object.hashCode() ); 
                converterMap.put( selectItemValue, object );
                return selectItemValue;
            }
    
            @Override
            public Object getAsObject(FacesContext context, UIComponent component, String selectItemValue){
                return converterMap.get(selectItemValue);
            }
    }
    

and bind to component with:

 <f:converter binding="#{viewScopedFacesConverter}" />

If you will use entity id rather than hashCode you can hit a collision- if you have few lists on one page for different entities (classes) with the same id

How can I remove the "No file chosen" tooltip from a file input in Chrome?

I look for good answer for this... and I found this:

First delete the 'no file chosen'

input[type="file"]{
font-size: 0px;
}

then work the button with the -webkit-file-upload-button, this way:

input[type="file"]::-webkit-file-input-button{
font-size: 16px; /*normal size*/
}

hope this is what you were looking for, it works for me.

What is the best way to implement nested dictionaries?

You can use recursion in lambdas and defaultdict, no need to define names:

a = defaultdict((lambda f: f(f))(lambda g: lambda:defaultdict(g(g))))

Here's an example:

>>> a['new jersey']['mercer county']['plumbers']=3
>>> a['new jersey']['middlesex county']['programmers']=81
>>> a['new jersey']['mercer county']['programmers']=81
>>> a['new jersey']['middlesex county']['salesmen']=62
>>> a
defaultdict(<function __main__.<lambda>>,
        {'new jersey': defaultdict(<function __main__.<lambda>>,
                     {'mercer county': defaultdict(<function __main__.<lambda>>,
                                  {'plumbers': 3, 'programmers': 81}),
                      'middlesex county': defaultdict(<function __main__.<lambda>>,
                                  {'programmers': 81, 'salesmen': 62})})})

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? myCursor.next() : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section: http://es.docs.mongodb.org/manual/core/cursors/

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

posts
{
 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "via":"facebook"
},
{
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},
 "via":"facebook"
}

and then:

db.posts.find({user.admin: 1 });

How to prevent colliders from passing through each other?

  • Edit ---> Project Settings ---> Time ... decrease "Fixed Timestep" value .. This will solve the problem but it can affect performance negatively.

  • Another solution is could be calculate the coordinates (for example, you have a ball and wall. Ball will hit to wall. So calculate coordinates of wall and set hitting process according these cordinates )

how to call an ASP.NET c# method using javascript

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

Import the jQuery library in your page mark-up:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

HTTP Error 503, the service is unavailable

In our case, nothing was logged (other than the HTTP error log entry for the 503), but the Enabled Protocols value for the web application in IIS had a typo in it! Instead of http,https there was a period in-between the protocols: http.https

Changing default encoding of Python?

You could change the encoding of your entire operating system. On Ubuntu you can do this with

sudo apt install locales 
sudo locale-gen en_US en_US.UTF-8    
sudo dpkg-reconfigure locales

Possible to iterate backwards through a foreach?

Elaborateling slighty on the nice answer by Jon Skeet, this could be versatile:

public static IEnumerable<T> Directional<T>(this IList<T> items, bool Forwards) {
    if (Forwards) foreach (T item in items) yield return item;
    else for (int i = items.Count-1; 0<=i; i--) yield return items[i];
}

And then use as

foreach (var item in myList.Directional(forwardsCondition)) {
    .
    .
}

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment

Creating a LINQ select from multiple tables

You must create a new anonymous type:

 select new { op, pg }

Refer to the official guide.

Postgres: SQL to list table foreign keys

None of the existing answers gave me results in the form that I actually wanted them in. So here is my (gargantuan) query for finding information about foreign keys.

A few notes:

  • The expressions used to generate from_cols and to_cols could be vastly simplified on Postgres 9.4 and later using WITH ORDINALITY rather than the window-function-using hackery I'm using.
  • Those same expressions are relying on the query planner not altering the returned order of results from UNNEST. I don't think it will, but I don't have any multiple-column foreign keys in my dataset to test with. Adding the 9.4 niceties eliminates this possibility altogether.
  • The query itself requires Postgres 9.0 or later (8.x didn't allow ORDER BY in aggregate functions)
  • Replace STRING_AGG with ARRAY_AGG if you want an array of columns rather than a comma-separated string.

-

SELECT
    c.conname AS constraint_name,
    (SELECT n.nspname FROM pg_namespace AS n WHERE n.oid=c.connamespace) AS constraint_schema,

    tf.name AS from_table,
    (
        SELECT STRING_AGG(QUOTE_IDENT(a.attname), ', ' ORDER BY t.seq)
        FROM
            (
                SELECT
                    ROW_NUMBER() OVER (ROWS UNBOUNDED PRECEDING) AS seq,
                    attnum
                FROM
                    UNNEST(c.conkey) AS t(attnum)
            ) AS t
            INNER JOIN pg_attribute AS a ON a.attrelid=c.conrelid AND a.attnum=t.attnum
    ) AS from_cols,

    tt.name AS to_table,
    (
        SELECT STRING_AGG(QUOTE_IDENT(a.attname), ', ' ORDER BY t.seq)
        FROM
            (
                SELECT
                    ROW_NUMBER() OVER (ROWS UNBOUNDED PRECEDING) AS seq,
                    attnum
                FROM
                    UNNEST(c.confkey) AS t(attnum)
            ) AS t
            INNER JOIN pg_attribute AS a ON a.attrelid=c.confrelid AND a.attnum=t.attnum
    ) AS to_cols,

    CASE confupdtype WHEN 'r' THEN 'restrict' WHEN 'c' THEN 'cascade' WHEN 'n' THEN 'set null' WHEN 'd' THEN 'set default' WHEN 'a' THEN 'no action' ELSE NULL END AS on_update,
    CASE confdeltype WHEN 'r' THEN 'restrict' WHEN 'c' THEN 'cascade' WHEN 'n' THEN 'set null' WHEN 'd' THEN 'set default' WHEN 'a' THEN 'no action' ELSE NULL END AS on_delete,
    CASE confmatchtype::text WHEN 'f' THEN 'full' WHEN 'p' THEN 'partial' WHEN 'u' THEN 'simple' WHEN 's' THEN 'simple' ELSE NULL END AS match_type,  -- In earlier postgres docs, simple was 'u'nspecified, but current versions use 's'imple.  text cast is required.

    pg_catalog.pg_get_constraintdef(c.oid, true) as condef
FROM
    pg_catalog.pg_constraint AS c
    INNER JOIN (
        SELECT pg_class.oid, QUOTE_IDENT(pg_namespace.nspname) || '.' || QUOTE_IDENT(pg_class.relname) AS name
        FROM pg_class INNER JOIN pg_namespace ON pg_class.relnamespace=pg_namespace.oid
    ) AS tf ON tf.oid=c.conrelid
    INNER JOIN (
        SELECT pg_class.oid, QUOTE_IDENT(pg_namespace.nspname) || '.' || QUOTE_IDENT(pg_class.relname) AS name
        FROM pg_class INNER JOIN pg_namespace ON pg_class.relnamespace=pg_namespace.oid
    ) AS tt ON tt.oid=c.confrelid
WHERE c.contype = 'f' ORDER BY 1;

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

In my case it turns out my
new server was running MySQL 5.5,
old server was running MySQL 5.6.
So I got this error when trying to import the .sql file I'd exported from my old server.

MySQL 5.5 does not support utf8mb4_unicode_520_ci, but
MySQL 5.6 does.

Updating to MySQL 5.6 on the new server solved collation the error !

If you want to retain MySQL 5.5, you can:
- make a copy of your exported .sql file
- replace instances of utf8mb4unicode520_ci and utf8mb4_unicode_520_ci
...with utf8mb4_unicode_ci
- import your updated .sql file.

Are multiple `.gitignore`s frowned on?

I can think of at least two situations where you would want to have multiple .gitignore files in different (sub)directories.

  • Different directories have different types of file to ignore. For example the .gitignore in the top directory of your project ignores generated programs, while Documentation/.gitignore ignores generated documentation.

  • Ignore given files only in given (sub)directory (you can use /sub/foo in .gitignore, though).

Please remember that patterns in .gitignore file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name applies to any file named name in given directory and all its subdirectories, while /name applies to file with this name only in given directory).

INSERT SELECT statement in Oracle 11G

Get rid of the values keyword and the parens. You can see an example here.

This is basic INSERT syntax:

INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);

This is the INSERT SELECT syntax:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

How do I remove all non alphanumeric characters from a string except dash?

Based on the answer for this question, I created a static class and added these. Thought it might be useful for some people.

public static class RegexConvert
{
    public static string ToAlphaNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z0-9]");
        return rgx.Replace(input, "");
    }

    public static string ToAlphaOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z]");
        return rgx.Replace(input, "");
    }

    public static string ToNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^0-9]");
        return rgx.Replace(input, "");
    }
}

Then the methods can be used as:

string example = "asdf1234!@#$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();

how to access the command line for xampp on windows

Run PHP file from command Promp.

Please set Environment Variable as per below mention steps.

  1. Right Click on MY Computer Icon and Click on Properties or Go to "Control Panel\System and Security\System".
  2. Select "Advanced System Settings" and select "Advance" Tab
  3. Now Select "Environment Variable" option and select "Path" from "System Variables" and click on "Edit" button
  4. Now set path where php.exe file is available - For example if XAMPP install in to C: drive then Path is "C:\xampp\php"
  5. After set path Click Ok and Apply.

Now open Command prompt where your source file are available and run command "php test.php"

Nested objects in javascript, best practices

var defaultsettings = {
    ajaxsettings: {
        ...
    },
    uisettings: {
        ...
    }
};

What rules does software version numbering follow?

The usual method I have seen is X.Y.Z, which generally corresponds to major.minor.patch:

  • Major version numbers change whenever there is some significant change being introduced. For example, a large or potentially backward-incompatible change to a software package.
  • Minor version numbers change when a new, minor feature is introduced or when a set of smaller features is rolled out.
  • Patch numbers change when a new build of the software is released to customers. This is normally for small bug-fixes or the like.

Other variations use build numbers as an additional identifier. So you may have a large number for X.Y.Z.build if you have many revisions that are tested between releases. I use a couple of packages that are identified by year/month or year/release. Thus, a release in the month of September of 2010 might be 2010.9 or 2010.3 for the 3rd release of this year.

There are many variants to versioning. It all boils down to personal preference.

For the "1.3v1.1", that may be two different internal products, something that would be a shared library / codebase that is rev'd differently from the main product; that may indicate version 1.3 for the main product, and version 1.1 of the internal library / package.

SQL - using alias in Group By

I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

SELECT 
 itemName as ItemName,
 FirstLetter,
 Count(itemName)
FROM table1
CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
GROUP BY itemName, FirstLetter

JSON parsing using Gson for Java

You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-

Gson gson = new GsonBuilder().create(); 
Response r = gson.fromJson(jsonString, Response.class);

Here is an example- http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html

List of lists into numpy array

Just use pandas

list(pd.DataFrame(listofstuff).melt().values)

this only works for a list of lists

if you have a list of list of lists you might want to try something along the lines of

lists(pd.DataFrame(listofstuff).melt().apply(pd.Series).melt().values)

How do I mount a host directory as a volume in docker compose

If you would like to mount a particular host directory (/disk1/prometheus-data in the following example) as a volume in the volumes section of the Docker Compose YAML file, you can do it as below, e.g.:

version: '3'

services:
  prometheus:
    image: prom/prometheus
    volumes:
      - prometheus-data:/prometheus

volumes:
  prometheus-data:
    driver: local
    driver_opts:
      o: bind
      type: none
      device: /disk1/prometheus-data

By the way, in prometheus's Dockerfile, You may find the VOLUME instruction as below, which marks it as holding externally mounted volumes from native host, etc. (Note however: this instruction is not a must though to mount a volume into a container.):

Dockerfile

...
VOLUME ["/prometheus"]
...

Refs:

How to change an Eclipse default project into a Java project

Open the .project file and add java nature and builders.

<projectDescription>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

And in .classpath, reference the Java libs:

<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

Microsoft Excel ActiveX Controls Disabled?

Here is the best answer that I have found on the Microsoft Excel Support Team Blog

For some users, Forms Controls (FM20.dll) are no longer working as expected after installing December 2014 updates. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.

You may received errors such as:

"Cannot insert object" "Object library invalid or contains references to object definitions that could not be found"

Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code. Steps to follow after the update:

To resolve this issue, you must delete the cached versions of the control type libraries (extender files) on the client computer. To do this, you must search your hard disk for files that have the ".exd" file name extension and delete all the .exd files that you find. These .exd files will be re-created automatically when you use the new controls the next time that you use VBA. These extender files will be under the user's profile and may also be in other locations, such as the following:

%appdata%\Microsoft\forms

%temp%\Excel8.0

%temp%\VBE

Scripting solution:

Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.

del %temp%\vbe\*.exd

del %temp%\excel8.0\*.exd

del %appdata%\microsoft\forms\*.exd

del %appdata%\microsoft\local\*.exd

del %appdata%\Roaming\microsoft\forms\*.exd

del %temp%\word8.0\*.exd

del %temp%\PPT11.0\*.exd

Additional step:

If the steps above do not resolve your issue, another step that can be tested (see warning below):

  1. On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.

    Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.

    Save and reopen the file. Test for resolution. If resolved, provide this updated project to additional users.

    Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.

If this does not resolve your issue, it may be a different issue and further troubleshooting may be necessary.

Microsoft is currently working on this issue. Watch the blog for updates.

Source

php $_GET and undefined index

Another option would be to suppress the PHP undefined index notice with the @ symbol in front of the GET variable like so:

$s = @$_GET['s'];

This will disable the notice. It is better to check if the variable has been set and act accordingly.

But this also works.

Insert all data of a datagridview to database at once

for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
                        SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
                        cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
                        cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
                        cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
                        cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
                        cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
                        cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
                        cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        MessageBox.Show("Added successfully!");

How to draw border around a UILabel?

it really depends on how many boarder use in your view , sometimes , just add a UIVIEW which the size is a bit bigger to create the border . the method is faster than produce a view

Read an Excel file directly from a R script

Yes. See the relevant page on the R wiki. Short answer: read.xls from the gdata package works most of the time (although you need to have Perl installed on your system -- usually already true on MacOS and Linux, but takes an extra step on Windows, i.e. see http://strawberryperl.com/). There are various caveats, and alternatives, listed on the R wiki page.

The only reason I see not to do this directly is that you may want to examine the spreadsheet to see if it has glitches (weird headers, multiple worksheets [you can only read one at a time, although you can obviously loop over them all], included plots, etc.). But for a well-formed, rectangular spreadsheet with plain numbers and character data (i.e., not comma-formatted numbers, dates, formulas with divide-by-zero errors, missing values, etc. etc. ..) I generally have no problem with this process.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

Clear the form field after successful submission of php form

If you want your form's field clear, you must only add a delay in the onClick event like:

<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"

onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear

document.getElementById("name").value = "";  <<<<<<just correct this
document.getElementById("telephone").value = "";    <<<<<correct this

By clearform(), I mean your clearing-fields function.

C++ calling base class constructors

The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.

Rectangle(int h,int w):
   Shape(h,w)
  {...}

Will call the other base class constructor.

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Solution to resolve issue in Local env's

I had my front-end code running in http://localhost:3000 and my API(Backend code) running at http://localhost:5000

Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.

let allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Headers', "*");
  next();
}
app.use(allowCrossDomain);

However you must restrict origins in case of other environments like stage, prod.

Strictly NO for higher environments.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Put novalidate="novalidate" on <form> tag.

<form novalidate="novalidate">
...
</form>

In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as <form novalidate="novalidate">.

http://www.w3schools.com/tags/att_form_novalidate.asp

How can a divider line be added in an Android RecyclerView?

Here is the code for a simple custom divider (vertical divider / 1dp height / black ):

It suppose you have Support Library:

compile "com.android.support:recyclerview-v7:25.1.1"

java code

    DividerItemDecoration divider = new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL);
    divider.setDrawable(ContextCompat.getDrawable(getBaseContext(), R.drawable.my_custom_divider));
    recyclerView.addItemDecoration(divider);

then the custom_divider.xml file sample :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:height="1dp" />
    <solid android:color="@android:color/black" />
</shape>

How to run multiple DOS commands in parallel?

if you have multiple parameters use the syntax as below. I have a bat file with script as below:

start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3 
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6 

This will open multiple consoles.

How to have the formatter wrap code with IntelliJ?

IntelliJ IDEA 14, 15, 2016 & 2017

Format existing code

  1. Ensure right margin is not exceeded

    File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded

    File Settings Ensure right margin

  2. Reformat code

    Code > Reformat code...

    Reformat code

    or press Ctrl + Alt + L

    warning If you have something like this:

    thisLineIsVeryLongAndWillBeChanged();   // comment
    

    it will be converted to

    thisLineIsVeryLongAndWillBeChanged();   
    // comment  
    

    instead of

    // comment  
    thisLineIsVeryLongAndWillBeChanged();   
    

    This is why I select pieces of code before reformatting if the code looks like in the previous example.

Wrap when typing reaches right margin

  • IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin

    Wrap when typing

  • IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing

    Wrap on typing

How to obtain the last index of a list?

I guess you want

last_index = len(list1) - 1 

which would store 3 in last_index.

Get resultset from oracle stored procedure

In SQL Plus:

SQL> var r refcursor
SQL> set autoprint on
SQL> exec :r := function_returning_refcursor();

Replace the last line with a call to your procedure / function and the contents of the refcursor will be displayed

Scraping html tables into R data frames using the XML package

library(RCurl)
library(XML)

# Download page using RCurl
# You may need to set proxy details, etc.,  in the call to getURL
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
# Process escape characters
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

# Parse the html tree, ignoring errors on the page
pagetree <- htmlTreeParse(webpage, error=function(...){})

# Navigate your way through the tree. It may be possible to do this more efficiently using getNodeSet
body <- pagetree$children$html$children$body 
divbodyContent <- body$children$div$children[[1]]$children$div$children[[4]]
tables <- divbodyContent$children[names(divbodyContent)=="table"]

#In this case, the required table is the only one with class "wikitable sortable"  
tableclasses <- sapply(tables, function(x) x$attributes["class"])
thetable  <- tables[which(tableclasses=="wikitable sortable")]$table

#Get columns headers
headers <- thetable$children[[1]]$children
columnnames <- unname(sapply(headers, function(x) x$children$text$value))

# Get rows from table
content <- c()
for(i in 2:length(thetable$children))
{
   tablerow <- thetable$children[[i]]$children
   opponent <- tablerow[[1]]$children[[2]]$children$text$value
   others <- unname(sapply(tablerow[-1], function(x) x$children$text$value)) 
   content <- rbind(content, c(opponent, others))
}

# Convert to data frame
colnames(content) <- columnnames
as.data.frame(content)

Edited to add:

Sample output

                     Opponent Played Won Drawn Lost Goals for Goals against  % Won
    1               Argentina     94  36    24   34       148           150  38.3%
    2                Paraguay     72  44    17   11       160            61  61.1%
    3                 Uruguay     72  33    19   20       127            93  45.8%
    ...

How to vertically align an image inside a div

Just for the sake of this being a valid answer I still want to post the jQuery solution again. This works for every element that has the v_align class applied to it. It will be vertical centered in the parent and on resizing of the window it will be recalculated.

Link to the JSFiddle

$(document).ready(function() {
  // Define the class that vertically aligns stuff
  var objects = '.v_align';
  // initial setup
  verticalAlign(objects);

  // Register resize event listener
  $(window).resize(function() {
    verticalAlign(objects);
  });
});

function verticalAlign(selector) {
  $(selector).each(function(val) {
    var parent_height = $(this).parent().height();
    var dif = parent_height - $(this).height()
    // Should only work if the parent is larger than the element
    var margin_top = dif > 0 ? dif/2 : 0;
    $(this).css("margin-top", margin_top + "px");
  });
}

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for

type(list_c)

considering you want the result as tuple out of list_a and list_b, do

tuple(zip(list_a,list_b)) 

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

hope this may help you:

SELECT  CAST(LoginTime AS DATE)
         FROM    AuditTrail 

If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

Python: Tuples/dictionaries as keys, select, sort

You want to use two keys independently, so you have two choices:

  1. Store the data redundantly with two dicts as {'banana' : {'blue' : 4, ...}, .... } and {'blue': {'banana':4, ...} ...}. Then, searching and sorting is easy but you have to make sure you modify the dicts together.

  2. Store it just one dict, and then write functions that iterate over them eg.:

    d = {'banana' : {'blue' : 4, 'yellow':6}, 'apple':{'red':1} }
    
    blueFruit = [(fruit,d[fruit]['blue']) if d[fruit].has_key('blue') for fruit in d.keys()]
    

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

How can I format a decimal to always show 2 decimal places?

If you're using this for currency, and also want the value to be seperated by ,'s you can use

$ {:,.f2}.format(currency_value).

e.g.:

currency_value = 1234.50

$ {:,.f2}.format(currency_value) --> $ 1,234.50

Here is a bit of code I wrote some time ago:

print("> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format(total_paid))

> At the end of year   1  total paid is         $ 43,806.36
> At the end of year   2  total paid is         $ 87,612.72
> At the end of year   3  total paid is         $ 131,419.08
> At the end of year   4  total paid is         $ 175,225.44
> At the end of year   5  total paid is         $ 219,031.80   <-- Note .80 and not .8
> At the end of year   6  total paid is         $ 262,838.16
> At the end of year   7  total paid is         $ 306,644.52
> At the end of year   8  total paid is         $ 350,450.88
> At the end of year   9  total paid is         $ 394,257.24
> At the end of year  10  total paid is         $ 438,063.60   <-- Note .60 and not .6
> At the end of year  11  total paid is         $ 481,869.96
> At the end of year  12  total paid is         $ 525,676.32
> At the end of year  13  total paid is         $ 569,482.68
> At the end of year  14  total paid is         $ 613,289.04
> At the end of year  15  total paid is         $ 657,095.40   <-- Note .40 and not .4  
> At the end of year  16  total paid is         $ 700,901.76
> At the end of year  17  total paid is         $ 744,708.12
> At the end of year  18  total paid is         $ 788,514.48
> At the end of year  19  total paid is         $ 832,320.84
> At the end of year  20  total paid is         $ 876,127.20   <-- Note .20 and not .2

How to get HTTP Response Code using Selenium WebDriver

For those people using Python, you might consider Selenium Wire, a library for inspecting requests made by the browser during a test.

You get access to requests via the driver.requests attribute:

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Go to the Google home page
driver.get('https://www.google.com')

# Access requests via the `requests` attribute
for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

Prints:

https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s&timestamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...

The library gives you the ability to access headers, status code, body content, as well as the ability to modify headers and rewrite URLs.

Adding values to an array in java

You always set x to 0 before changing array's value.

You can use:

int[] tall = new int[28123];

for (int j = 0;j<28123;j++){
    // Or whatever value you want to set.
    tall[j] = j + 1;
}

Or just remove the initialization of x (int x=0) before the for loop.

Git error on git pull (unable to update local ref)

Speaking from a PC user - Reboot.

Honestly, it worked for me. I've solved two strange git issues I thought were corruptions this way.

Secure hash and salt for PHP passwords

THINGS TO REMEMBER

A lot has been said about Password encryption for PHP, most of which is very good advice, but before you even start the process of using PHP for password encryption make sure you have the following implemented or ready to be implemented.

SERVER

PORTS

No matter how good your encryption is if you don't properly secure the server that runs the PHP and DB all your efforts are worthless. Most servers function relatively the same way, they have ports assigned to allow you to access them remotely either through ftp or shell. Make sure that you change the default port of which ever remote connection you have active. By not doing this you in effect have made the attacker do one less step in accessing your system.

USERNAME

For all that is good in the world do not use the username admin, root or something similar. Also if you are on a unix based system DO NOT make the root account login accessible, it should always be sudo only.

PASSWORD

You tell your users to make good passwords to avoid getting hacked, do the same. What is the point in going through all the effort of locking your front door when you have the backdoor wide open.

DATABASE

SERVER

Ideally you want your DB and APPLICATION on separate servers. This is not always possible due to cost, but it does allow for some safety as the attacker will have to go through two steps to fully access the system.

USER

Always have your application have its own account to access the DB, and only give it the privileges it will need.

Then have a separate user account for you that is not stored anywhere on the server, not even in the application.

Like always DO NOT make this root or something similar.

PASSWORD

Follow the same guidelines as with all good passwords. Also don't reuse the same password on any SERVER or DB accounts on the same system.

PHP

PASSWORD

NEVER EVER store a password in your DB, instead store the hash and unique salt, I will explain why later.

HASHING

ONE WAY HASHING!!!!!!!, Never hash a password in a way that it can be reversed, Hashes should be one way, meaning you don't reverse them and compare them to the password, you instead hash the entered password the same way and compare the two hashes. This means that even if an attacker gets access to the DB he doesn't know what the actually password is, just its resulting hash. Which means more security for your users in the worst possible scenario.

There are a lot of good hashing functions out there (password_hash, hash, etc...) but you need to select a good algorithm for the hash to be effective. (bcrypt and ones similar to it are decent algorithms.)

When hashing speed is the key, the slower the more resistant to Brute Force attacks.

One of the most common mistakes in hashing is that hashes are not unique to the users. This is mainly because salts are not uniquely generated.

SALTING

Passwords should always be salted before hashed. Salting adds a random string to the password so similar passwords don't appear the same in the DB. However if the salt is not unique to each user (ie: you use a hard coded salt) than you pretty much have made your salt worthless. Because once an attacker figures out one password salt he has the salt for all of them.

When you create a salt make sure it is unique to the password it is salting, then store both the completed hash and salt in your DB. What this will do is make it so that an attacker will have to individually crack each salt and hash before they can gain access. This means a lot more work and time for the attacker.

USERS CREATING PASSWORDS

If the user is creating a password through the frontend that means it has to be sent to the server. This opens up a security issue because that means the unencrypted password is being sent to the server and if a attacker is able to listen and access that all your security in PHP is worthless. ALWAYS transmit the data SECURELY, this is done through SSL, but be weary even SSL is not flawless (OpenSSL's Heartbleed flaw is an example of this).

Also make the user create a secure password, it is simple and should always be done, the user will be grateful for it in the end.

Finally, no matter the security measures you take nothing is 100% secure, the more advanced the technology to protect becomes the more advanced the attacks become. But following these steps will make your site more secure and far less desirable for attackers to go after.

Here is a PHP class that creates a hash and salt for a password easily

http://git.io/mSJqpw

Checking for an empty file in C++

Ok, so this piece of code should work for you. I changed the names to match your parameter.

inFile.seekg(0, ios::end);  
if (inFile.tellg() == 0) {    
  // ...do something with empty file...  
}

Bash scripting, multiple conditions in while loop

The correct options are (in increasing order of recommendation):

# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))

Some notes:

  1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

  2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

If you open the directory which it is trying to delete then also you will face same error so first close the folder.

Saving timestamp in mysql table using php

Datatype 'bigint unsigned' may suit this requirement.

How to implement common bash idioms in Python?

I have published a package on PyPI: ez.
Use pip install ez to install it.

It has packed common commands in shell and nicely my lib uses basically the same syntax as shell. e.g., cp(source, destination) can handle both file and folder! (wrapper of shutil.copy shutil.copytree and it decides when to use which one). Even more nicely, it can support vectorization like R!

Another example: no os.walk, use fls(path, regex) to recursively find files and filter with regular expression and it returns a list of files with or without fullpath

Final example: you can combine them to write very simply scripts:
files = fls('.','py$'); cp(files, myDir)

Definitely check it out! It has cost me hundreds of hours to write/improve it!

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How to map and remove nil values in Ruby

In your example:

items.map! { |x| process_x url } # [1, 2, 3, 4, 5] => [1, nil, 3, nil, nil]

it does not look like the values have changed other than being replaced with nil. If that is the case, then:

items.select{|x| process_x url}

will suffice.

How to let PHP to create subdomain automatically for each user?

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.

Mapping list in Yaml to list of objects in Spring Boot

I had much issues with this one too. I finally found out what's the final deal.

Referring to @Gokhan Oner answer, once you've got your Service class and the POJO representing your object, your YAML config file nice and lean, if you use the annotation @ConfigurationProperties, you have to explicitly get the object for being able to use it. Like :

@ConfigurationProperties(prefix = "available-payment-channels-list")
//@Configuration  <-  you don't specificly need this, instead you're doing something else
public class AvailableChannelsConfiguration {

    private String xyz;
    //initialize arraylist
    private List<ChannelConfiguration> channelConfigurations = new ArrayList<>();

    public AvailableChannelsConfiguration() {
        for(ChannelConfiguration current : this.getChannelConfigurations()) {
            System.out.println(current.getName()); //TADAAA
        }
    }

    public List<ChannelConfiguration> getChannelConfigurations() {
        return this.channelConfigurations;
    }

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;
    }

}

And then here you go. It's simple as hell, but we have to know that we must call the object getter. I was waiting at initialization, wishing the object was being built with the value but no. Hope it helps :)

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

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

My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.

Push and set upstream (remote) repository as origin:

$ git push -u origin

Next time you push, you don't have to specify the remote repository:

$ git push

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

Getting a HeadlessException: No X11 DISPLAY variable was set

Your system does not have a GUI manager. Happens mostly in Solaris/Linux boxes. If you are using GUI in them make sure that you have a GUI manager installed and you may also want to google through the DISPLAY variable.

Is there a way to comment out markup in an .ASPX page?

Another way assuming it's not server side code you want to comment out is...

<asp:panel runat="server" visible="false">
    html here
</asp:panel>

How to execute UNION without sorting? (SQL)

select T.Col1, T.Col2, T.Sort
from 
    (
      select T.Col1,
             T.Col2,
             T.Sort,
             rank() over(partition by T.Col1, T.Col2 order by T.Sort) as rn
      from
          (
            select Col1, Col2, 1 as Sort
            from Table1
            union all
            select Col1, Col2, 2
            from Table2
          ) as T
    ) as T
where T.rn = 1    
order by T.Sort

Is it possible to indent JavaScript code in Notepad++?

Could you use online services like this ?

Update: (as per request)

Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html

How do I align a number like this in C?

Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

Hide text using css

This is actually an area ripe for discussion, with many subtle techniques available. It is important that you select/develop a technique that meets your needs including: screen readers, images/css/scripting on/off combinations, seo, etc.

Here are some good resources to get started down the road of standardista image replacement techniques:

http://faq.css-standards.org/Image_Replacement

http://www.alistapart.com/articles/fir

http://veerle.duoh.com/blog/links/#l-10

How to remove commits from a pull request

You have several techniques to do it.

This post - read the part about the revert will explain in details what we want to do and how to do it.

Here is the most simple solution to your problem:

# Checkout the desired branch
git checkout <branch>

# Undo the desired commit
git revert <commit>

# Update the remote with the undo of the code
git push origin <branch>

The revert command will create a new commit with the undo of the original commit.

Not Equal to This OR That in Lua

For testing only two values, I'd personally do this:

if x ~= 0 and x ~= 1 then
    print( "X must be equal to 1 or 0" )
    return
end

If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:

choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}

if not choices[x] then
    print("x must be in the first six prime numbers")
    return
end

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Enabling HTTPS on express.js

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);

How to convert a string to an integer in JavaScript?

Please see the below example.It will help clear your doubt

Example                  Result

parseInt("4")            4
parseInt("5aaa")         5
parseInt("4.33333")      4
parseInt("aaa");         NaN (means "Not a Number")

by using parseint function It will only give op of integer present and not the string

show distinct column values in pyspark dataframe: python

If you want to see the distinct values of a specific column in your dataframe , you would just need to write -

    df.select('colname').distinct().show(100,False)

This would show the 100 distinct values (if 100 values are available) for the colname column in the df dataframe.

If you want to do something fancy on the distinct values, you can save the distinct values in a vector

    a = df.select('colname').distinct()

Here, a would have all the distinct values of the column colname

Go: panic: runtime error: invalid memory address or nil pointer dereference

for me one solution for this problem was to add in sql.Open ... sslmode=disable

Android customized button; changing text color

Create a stateful color for your button, just like you did for background, for example:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Focused and not pressed -->
    <item android:state_focused="true" 
          android:state_pressed="false" 
          android:color="#ffffff" />

    <!-- Focused and pressed -->
    <item android:state_focused="true" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Unfocused and pressed -->
    <item android:state_focused="false" 
          android:state_pressed="true" 
          android:color="#000000" />

    <!-- Default color -->
    <item android:color="#ffffff" />

</selector>

Place the xml in a file at res/drawable folder i.e. res/drawable/button_text_color.xml. Then just set the drawable as text color:

android:textColor="@drawable/button_text_color"

Git: Find the most recent common ancestor of two branches

git diff master...feature

shows all the new commits of your current (possibly multi-commit) feature branch.

man git-diff documents that:

git diff A...B

is the same as:

git diff $(git merge-base A B) B

but the ... is easier to type and remember.

As mentioned by Dave, the special case of HEAD can be omitted. So:

git diff master...HEAD

is the same as:

git diff master...

which is enough if the current branch is feature.

Finally, remember that order matters! Doing git diff feature...master will show changes that are on master not on feature.

I wish more git commands would support that syntax, but I don't think they do. And some even have different semantics for ...: What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?

Error: 'int' object is not subscriptable - Python

x is already integer(x=0) and again you trying to make x again integer and also you gave indexing which is beyound the limit because x already has only one indexing (0) and you are trying to give indexing same as age so thats why you get this error. use this simple code

name1 = input("What's your name? ")
age1 = int(input ("how old are you?" ))
x=0
twentyone = str(21-age1)
print("Hi, " +name1+ " you will be 21 in: " + twentyone + " years.")

How can I trigger a JavaScript event click

I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.

The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):

var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
  l.click();
}

This will generate the required result