Programs & Examples On #Server variables

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

Assuming one has a simple setup (CentOS 7, Apache 2.4.x, and PHP 5.6.20) and only one website (not assuming virtual hosting) ...

In the PHP sense, $_SERVER['SERVER_NAME'] is an element PHP registers in the $_SERVER superglobal based on your Apache configuration (**ServerName** directive with UseCanonicalName On ) in httpd.conf (be it from an included virtual host configuration file, whatever, etc ...). HTTP_HOST is derived from the HTTP host header. Treat this as user input. Filter and validate before using.

Here is an example of where I use $_SERVER['SERVER_NAME'] as the basis for a comparison. The following method is from a concrete child class I made named ServerValidator (child of Validator). ServerValidator checks six or seven elements in $_SERVER before using them.

In determining if the HTTP request is POST, I use this method.

public function isPOST()
{
    return (($this->requestMethod === 'POST')    &&  // Ignore
            $this->hasTokenTimeLeft()            &&  // Ignore
            $this->hasSameGETandPOSTIdentities() &&  // Ingore
            ($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')));
}

By the time this method is called, all filtering and validating of relevant $_SERVER elements would have occurred (and relevant properties set).

The line ...

($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')

... checks that the $_SERVER['HTTP_HOST'] value (ultimately derived from the requested host HTTP header) matches $_SERVER['SERVER_NAME'].

Now, I am using superglobal speak to explain my example, but that is just because some people are unfamiliar with INPUT_GET, INPUT_POST, and INPUT_SERVER in regards to filter_input_array().

The bottom line is, I do not handle POST requests on my server unless all four conditions are met. Hence, in terms of POST requests, failure to provide an HTTP host header (presence tested for earlier) spells doom for strict HTTP 1.0 browsers. Moreover, the requested host must match the value for ServerName in the httpd.conf, and, by extention, the value for $_SERVER('SERVER_NAME') in the $_SERVER superglobal. Again, I would be using INPUT_SERVER with the PHP filter functions, but you catch my drift.

Keep in mind that Apache frequently uses ServerName in standard redirects (such as leaving the trailing slash off a URL: Example, http://www.example.com becoming http://www.example.com/), even if you are not using URL rewriting.

I use $_SERVER['SERVER_NAME'] as the standard, not $_SERVER['HTTP_HOST']. There is a lot of back and forth on this issue. $_SERVER['HTTP_HOST'] could be empty, so this should not be the basis for creating code conventions such as my public method above. But, just because both may be set does not guarantee they will be equal. Testing is the best way to know for sure (bearing in mind Apache version and PHP version).

How to find the most recent file in a directory using .NET, and without looping?

Another approach if you are using Directory.EnumerateFiles and want to read files in latest modified by first.

foreach (string file in Directory.EnumerateFiles(fileDirectory, fileType).OrderByDescending(f => new FileInfo(f).LastWriteTime))

}

How to get back Lost phpMyAdmin Password, XAMPP

Unless you have changed your password the default setting dont require you to enter a password to connect to the MYSQL server, try:

mysql_connect('localhost','root','');

if not then you can export your databases to a external file, just follow these instructions.

http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html

if you are unable to access phpMyAdmin then try,

http://www.simplehelp.net/2008/11/26/how-to-reset-a-lost-mysql-root-password/

jQuery bind to Paste Event, how to get the content of the paste

There is an onpaste event that works in modern day browsers. You can access the pasted data using the getData function on the clipboardData object.

$("#textareaid").bind("paste", function(e){
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    alert(pastedData);
} );

Note that bind and unbind are deprecated as of jQuery 3. The preferred call is to on.

All modern day browsers support the Clipboard API.

See also: In Jquery How to handle paste?

Show DataFrame as table in iPython Notebook

from IPython.display import display
display(df)  # OR
print df.to_html()

System.web.mvc missing

Just in case someone is a position where he get's the same error. In my case downgrading Microsoft.AspNet.Mvc and then upgrading it again helped. I had this problem after installing Glimpse and removing it. System.Web.Mvc was references wrong somehow, cleaning the solution or rebuilding it didin't worked in my case. Just give it try if none of the above answers works for you.

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

"R cannot be resolved to a variable"?

Problem was eclipse was not generating R.java. To resolve this issue please go to project->clean... and select your project and select ok and then clean and build project and import your package name R file(Ex com.demo.R). It works.

Ignore python multiple return value

You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.

If you want to get multiple values at a time, use something like x, y = func()[2:4].

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

Obtain form input fields using jQuery?

Associative? Not without some work, but you can use generic selectors:

var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});

Cutting the videos based on start and end time using ffmpeg

Even though I'm 6 years late, but I think all the answers above didn't properly address the question @kalai is asking. The bash script below will process a text file in the following format:

URL | start_time | end_time | filename

for example

https://www.youtube.com/watch?v=iUDURCrvrMI|00:02:02|00:03:41|1

and loop through the file, downloads the file that youtube-dl supports, calculating duration between start_time and end_time and passing it to ffmpeg, since -t is actually the duration, not the real end_time

Hit me up if you have any question.

    for i in $(<video.txt);
    do
        URL=`echo $i | cut -d "|" -f 1`;
        START=`echo $i | cut -d "|" -f 2`;
        END=`echo $i | cut -d "|" -f 3`;
        FILE=`echo $i | cut -d "|" -f 4`;

        SEC1=`echo $START | sed 's/^/((/; s/:/)*60+/g' | bc`
        SEC2=`echo $END | sed 's/^/((/; s/:/)*60+/g' | bc`

        DIFFSEC=`expr ${SEC2} - ${SEC1}`

        ffmpeg $(youtube-dl -g $URL | sed "s/.*/-ss $START -i &/") -t $DIFFSEC -c copy $FILE".mkv";
        ffmpeg -i $FILE".mkv" -f mp3 -ab 192000 -vn $FILE".mp3";
        rm $FILE".mkv";
    done;

Laravel Eloquent: How to get only certain columns from joined tables

Using Model:

Model::where('column','value')->get(['column1','column2','column3',...]);

Using Query Builder:

DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);

Can you control how an SVG's stroke-width is drawn?

I found an easy way, which has a few restrictions, but worked for me:

  • define the shape in defs
  • define a clip path referencing the shape
  • use it and double the stroke with as the outside is clipped

Here a working example:

_x000D_
_x000D_
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
 <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
 <clipPath id="clip">_x000D_
  <use xlink:href="#ld"/>_x000D_
 </clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
 <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

As I answered here, you can remove spines from all your plots through style settings (style sheet or rcParams):

import matplotlib as mpl

mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

Can I set the height of a div based on a percentage-based width?

I made a CSS approach to this that is sized by the viewport width, but maxes out at 100% of the viewport height. It doesn't require box-sizing:border-box. If a pseudo element cannot be used, the pseudo-code's CSS can be applied to a child. Demo

.container {
  position: relative;
  max-width:100vh;
  max-height:100%;
  margin:0 auto;
  overflow: hidden;
}
.container:before {
  content: "";
  display: block;
  margin-top: 100%;
}
.child {
  position: absolute;
  top: 0;
  left: 0;
}

Support table for viewport units

I wrote about this approach and others in a CSS-Tricks article on scaling responsive animations that you should check out.

setBackground vs setBackgroundDrawable (Android)

I also had this problem, but I made a workaround using a ImageView.

Try using a RelativeLayout and add a ImageView inside it (width and height: fill_parent, scaleType: center).

Also make sure the imageview is the first element inside the RelativeLayout, so it will act as background.

Resize image in the wiki of GitHub using Markdown

I have used methods described above. Now I am using the method which is a way similiar but more simple to me.

  1. First create add README.md file to your project.
  2. Then upload screenshoots or whatever description images needed to your project main directory.
  3. After uploading image Assets use html to refer these assets directly without using link like below

Like this:

<img src="icon.jpg" width="324" height="324">

<p align="center">
  <img src="screen1.png" width="256" height="455">
  <img src="screen2.png" width="256" height="455">
  <img src="screen3.png" width="256" height="455">
</p>

On above example I have used paragraph to align images side by side. If you are going to use single image just use the code as below

<img src="icon.jpg" width="324" height="324">

Have a nice day!

How do I iterate over a JSON structure?

Use for...of:

_x000D_
_x000D_
var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}
_x000D_
_x000D_
_x000D_

Result:

Susita
BMW

Identify duplicate values in a list in Python

I tried below code to find duplicate values from list

1) create a set of duplicate list

2) Iterated through set by looking in duplicate list.

glist=[1, 2, 3, "one", 5, 6, 1, "one"]
x=set(glist)
dup=[]
for c in x:
    if(glist.count(c)>1):
        dup.append(c)
print(dup)

OUTPUT

[1, 'one']

Now get the all index for duplicate element

glist=[1, 2, 3, "one", 5, 6, 1, "one"]
x=set(glist)
dup=[]
for c in x:
    if(glist.count(c)>1):
        indices = [i for i, x in enumerate(glist) if x == c]
        dup.append((c,indices))
print(dup)

OUTPUT

[(1, [0, 6]), ('one', [3, 7])]

Hope this helps someone

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Convert RGB values to Integer

int rgb = new Color(r, g, b).getRGB();

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

How to SELECT a dropdown list item by value programmatically

For those who come here by search (because this thread is over 3 years old):

string entry // replace with search value

if (comboBox.Items.Contains(entry))
   comboBox.SelectedIndex = comboBox.Items.IndexOf(entry);
else
   comboBox.SelectedIndex = 0;

What is the best way to test for an empty string with jquery-out-of-the-box?

To checks for all 'empties' like null, undefined, '', ' ', {}, [].

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

How to display a "busy" indicator with jQuery?

To extend Rodrigo's solution a little - for requests that are executed frequently, you may only want to display the loading image if the request takes more than a minimum time interval, otherwise the image will be continually popping up and quickly disappearing

var loading = false;

$.ajaxSetup({
    beforeSend: function () {
        // Display loading icon if AJAX call takes >1 second
        loading = true;
        setTimeout(function () {
            if (loading) {
                // show loading image
            }
        }, 1000);            
    },
    complete: function () {
        loading = false;
        // hide loading image
    }
});

Does MySQL ignore null values on unique constraints?

A simple answer would be : No, it doesn't

Explanation : According to the definition of unique constraints (SQL-92)

A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns

This statement can have two interpretations as :

  • No two rows can have same values i.e. NULL and NULL is not allowed
  • No two non-null rows can have values i.e NULL and NULL is fine, but StackOverflow and StackOverflow is not allowed

Since MySQL follows second interpretation, multiple NULL values are allowed in UNIQUE constraint column. Second, if you would try to understand the concept of NULL in SQL, you will find that two NULL values can be compared at all since NULL in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL values in UNIQUE constraint column, you are contracting the meaning of NULL in SQL. I would summarise my answer by saying :

MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values

What are best practices for REST nested resources?

I've moved what I've done from the question to an answer where more people are likely to see it.

What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.

So in this example (just listing the endpoints that change a resource)

  • POST /companies/ creates a new company returns a link to the created company.
  • POST /companies/{companyId}/departments when a department is put creates the new department returns a link to /departments/{departmentId}
  • PUT /departments/{departmentId} modifies a department
  • POST /departments/{deparmentId}/employees creates a new employee returns a link to /employees/{employeeId}

So there are root level resources for each of the collections. However the create is in the owning object.

Prime numbers between 1 to 100 in C Programming Language

#include <stdio.h>
#include <conio.h>
int main()
{
    int i,j;
    int b=0;
    for (i=2;i<=100;i++){
        for (j=2;j<=i;j++){
            if (i%j==0){
                break;
            }
        }
        if (i==j)
            print f("\n%d",j);
    }
    getch ();
}

Why should you use strncpy instead of strcpy?

That depends on our requirement. For windows users

We use strncpy whenever we don't want to copy entire string or we want to copy only n number of characters. But strcpy copies the entire string including terminating null character.

These links will help you more to know about strcpy and strncpy and where we can use.

about strcpy

about strncpy

Placing border inside of div and not on its edge

Probably it is belated answer, but I want to share with my findings. I found 2 new approaches to this problem that I have not found here in the answers:

Inner border through box-shadow css property

Yes, box-shadow is used to add box-shadows to the elements. But you can specify inset shadow, that would look like a inner border rather like a shadow. You just need to set horizontal and vertical shadows to 0px, and the "spread" property of the box-shadow to the width of the border you want to have. So for the 'inner' border of 10px you would write the following:

div{
    width:100px;
    height:100px;
    background-color:yellow;
    box-shadow:0px 0px 0px 10px black inset;
    margin-bottom:20px;
}

Here is jsFiddle example that illustrates the difference between box-shadow border and 'normal' border. This way your border and the box width are of total 100px including the border.

More about box-shadow:here

Border through outline css property

Here is another approach, but this way the border would be outside of the box. Here is an example. As follows from the example, you can use css outline property, to set the border that does not affect the width and height of the element. This way, the border width is not added to the width of an element.

div{
   width:100px;
   height:100px;
   background-color:yellow;
   outline:10px solid black;
}

More about outline: here

A regex for version number parsing

I'd express the format as:

"1-3 dot-separated components, each numeric except that the last one may be *"

As a regexp, that's:

^(\d+\.)?(\d+\.)?(\*|\d+)$

[Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It's a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups.

In my solution, the groups capture the "." characters. This can be dealt with using non-capturing groups as in ajborley's answer.

Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported.

Perl code to deal with both issues after the regexp could be something like this:

@version = ();
@groups = ($1, $2, $3);
foreach (@groups) {
    next if !defined;
    s/\.//;
    push @version, $_;
}
($major, $minor, $mod) = (@version, "*", "*");

Which isn't really any shorter than splitting on "." ]

Visual Studio: How to show Overloads in IntelliSense?

Mine showed up in VS2010 after writing the first parenthesis..

so, prams.Add(

After doings something like that, the box with the up and down arrows appeared.

How to get the first word of a sentence in PHP?

All of the answers here are using an approach that the processor needs to search all of the string even if the first word is found! For big strings, this is not recommended. This approach is optimal:

function getFirstWord($string) {
    $result = "";
    foreach($string as $char) {
        if($char == " " && strlen($result)) {
            break;
        }
        $result .= $char;
    }
    return $result;
}

Show/Hide Div on Scroll

i have a pretty answer try this code ;)

<div id="DivID">
</div>

$("#DivID").scrollview({ direction: 'y' });
$("#DivID > .ui-scrollbar").addClass("ui-scrollbar-visible");

IOS: verify if a point is inside a rect

It is so simple,you can use following method to do this kind of work:-

-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect
{
    if ( CGRectContainsPoint(rect,point))
        return  YES;// inside
    else
        return  NO;// outside
}

In your case,you can pass imagView.center as point and another imagView.frame as rect in about method.

You can also use this method in bellow UITouch Method :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I think that this happens when javascript debugging is enabled in visual studio and at the same time the chrome developer tools debugger is enabled. The problem arises because two different debuggers trying to debug the same process.

How to remove ASP.Net MVC Default HTTP Headers?

Check this blog Don't use code to remove headers. It is unstable according Microsoft

My take on this:

<system.webServer>          
    <httpProtocol>
    <!-- Security Hardening of HTTP response headers -->
    <customHeaders>
        <!--Sending the new X-Content-Type-Options response header with the value 'nosniff' will prevent 
                Internet Explorer from MIME-sniffing a response away from the declared content-type. -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- X-Frame-Options tells the browser whether you want to allow your site to be framed or not. 
                 By preventing a browser from framing your site you can defend against attacks like clickjacking. 
                 Recommended value "x-frame-options: SAMEORIGIN" -->
        <add name="X-Frame-Options" value="SAMEORIGIN" />

        <!-- Setting X-Permitted-Cross-Domain-Policies header to “master-only” will instruct Flash and PDF files that 
                 they should only read the master crossdomain.xml file from the root of the website. 
                 https://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
        <add name="X-Permitted-Cross-Domain-Policies" value="master-only" />

        <!-- X-XSS-Protection sets the configuration for the cross-site scripting filter built into most browsers. 
                 Recommended value "X-XSS-Protection: 1; mode=block". -->
        <add name="X-Xss-Protection" value="1; mode=block" />

        <!-- Referrer-Policy allows a site to control how much information the browser includes with navigations away from a document and should be set by all sites. 
                 If you have sensitive information in your URLs, you don't want to forward to other domains 
                 https://scotthelme.co.uk/a-new-security-header-referrer-policy/ -->
        <add name="Referrer-Policy" value="no-referrer-when-downgrade" />

        <!-- Remove x-powered-by in the response header, required by OWASP A5:2017 - Do not disclose web server configuration -->
        <remove name="X-Powered-By" />

        <!-- Ensure the cache-control is public, some browser won't set expiration without that  -->
        <add name="Cache-Control" value="public" />
    </customHeaders>
</httpProtocol>

<!-- Prerequisite for the <rewrite> section
            Install the URL Rewrite Module on the Web Server https://www.iis.net/downloads/microsoft/url-rewrite -->
<rewrite>
    <!-- Remove Server response headers (OWASP Security Measure) -->
    <outboundRules rewriteBeforeCache="true">
        <rule name="Remove Server header">
            <match serverVariable="RESPONSE_Server" pattern=".+" />

            <!-- Use custom value for the Server info -->
            <action type="Rewrite" value="Your Custom Value Here." />
        </rule>
    </outboundRules>
</rewrite>
</system.webServer>

AngularJS : How to watch service variables?

Have a look at this plunker:: this is the simplest example i could think of

http://jsfiddle.net/HEdJF/

<div ng-app="myApp">
    <div ng-controller="FirstCtrl">
        <input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
        <br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
    </div>
    <hr>
    <div ng-controller="SecondCtrl">
        Input should also be here: {{Data.FirstName}}<!-- How do I automatically updated it here? -->
    </div>
</div>



// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
   return { FirstName: '' };
});

myApp.controller('FirstCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

myApp.controller('SecondCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

Best way of invoking getter by reflection

You can use Reflections framework for this

import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

ApiNotActivatedMapError for simple html page using google-places-api

Assuming you already have a application created under google developer console, Follow the below steps

  1. Go to the following link https://console.cloud.google.com/apis/dashboard? you will be getting the below page enter image description here
  2. Click on ENABLE APIS AND SERVICES you will be directed to following page enter image description here
  3. Select the desired option - in this case "Maps JavaScript API"
  4. Click ENABLE button as below, enter image description here

Note: Please use a server to load the html file

How can I remove text within parentheses with a regex?

If you can stand to use sed (possibly execute from within your program, it'd be as simple as:

sed 's/(.*)//g'

How do you use script variables in psql?

FWIW, the real problem was that I had included a semicolon at the end of my \set command:

\set owner_password 'thepassword';

The semicolon was interpreted as an actual character in the variable:

\echo :owner_password thepassword;

So when I tried to use it:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

...I got this:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").

The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

Not automatically, no. You can create a project template as BlueWandered suggested or create a custom property sheet that you can use for your current and all future projects.

  1. Open up the Property Manager (View->Property Manager)
  2. In the Property Manager Right click on your project and select "Add New Project Property Sheet"
  3. Give it a name and create it in a common directory. The property sheet will be added to all build targets.
  4. Right click on the new property sheet and select "Properties". This will open up the properties and allow you to change the settings just like you would if you were editing them for a project.
  5. Go into "Common Properties->C/C++->Preprocessor"
  6. Edit the setting "Preprocessor Definitions" and add _CRT_SECURE_NO_WARNINGS.
  7. Save and you're done.

Now any time you create a new project, add this property sheet like so...

  1. Open up the Property Manager (View->Property Manager)
  2. In the Property Manager Right click on your project and select "Add Existing Project Property Sheet"

The benefit here is that not only do you get a single place to manage common settings but anytime you change the settings they get propagated to ALL projects that use it. This is handy if you have a lot of settings like _CRT_SECURE_NO_WARNINGS or libraries like Boost that you want to use in your projects.

How do I find the location of my Python site-packages directory?

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(or just first item with site.getsitepackages()[0])

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

How to reference image resources in XAML?

If the image is in your resources folder and its build action is set to Resource. You can reference the image in XAML as follows:

"pack://application:,,,/Resources/Search.png"

Assuming you do not have any folder structure under the Resources folder and it is an application. For example I use:

ImageSource="pack://application:,,,/Resources/RibbonImages/CloseButton.png"

when I have a folder named RibbonImages under Resources folder.

ng: command not found while creating new project using angular-cli

In my case, it was happening when I restarted working on an adjacent tab. It was the npm which was not set. Please check the version of npm wither using

npm -v

or if you are having nvm then

nvm list

or

nvm current

I set it to 8.9.1 and then it started working again. I hope it helps.

How do I show the changes which have been staged?

It should just be:

git diff --cached

--cached means show the changes in the cache/index (i.e. staged changes) against the current HEAD. --staged is a synonym for --cached.

--staged and --cached does not point to HEAD, just difference with respect to HEAD. If you cherry pick what to commit using git add --patch (or git add -p), --staged will return what is staged.

Jquery function BEFORE form submission

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>

How can I pair socks from a pile efficiently?

In order to say how efficient it is to pair socks from a pile, we have to define the machine first, because the pairing isn't done whether by a turing nor by a random access machine, which are normally used as the basis for an algorithmic analysis.

The machine

The machine is an abstraction of a the real world element called human being. It is able to read from the environment via a pair of eyes. And our machine model is able to manipulate the environment by using 2 arms. Logical and arithmetic operations are calculated using our brain (hopefully ;-)).

We also have to consider the intrinsic runtime of the atomic operations that can be carried out with these instruments. Due to physical constraints, operations which are carried out by an arm or eye have non constant time complexity. This is because we can't move an endlessly large pile of socks with an arm nor can an eye see the top sock on an endlessly large pile of socks.

However mechanical physics give us some goodies as well. We are not limited to move at most one sock with an arm. We can move a whole couple of them at once.

So depending on the previous analysis following operations should be used in descending order:

  • logical and arithmetic operations
  • environmental reads
  • environmental modifications

We can also make use of the fact that people only have a very limited amount of socks. So an environmental modification can involve all socks in the pile.

The algorithm

So here is my suggestion:

  1. Spread all socks in the pile over the floor.
  2. Find a pair by looking at the socks on the floor.
  3. Repeat from 2 until no pair can be made.
  4. Repeat from 1 until there are no socks on the floor.

Operation 4 is necessary, because when spreading socks over the floor some socks may hide others. Here is the analysis of the algorithm:

The analysis

The algorithm terminates with high probability. This is due to the fact that one is unable to find pairs of socks in step number 2.

For the following runtime analysis of pairing n pairs of socks, we suppose that at least half of the 2n socks aren't hidden after step 1. So in the average case we can find n/2 pairs. This means that the loop is step 4 is executed O(log n) times. Step 2 is executed O(n^2) times. So we can conclude:

  • The algorithm involves O(ln n + n) environmental modifications (step 1 O(ln n) plus picking every pair of sock from the floor)
  • The algorithm involves O(n^2) environmental reads from step 2
  • The algorithm involves O(n^2) logical and arithmetic operations for comparing a sock with another in step 2

So we have a total runtime complexity of O(r*n^2 + w*(ln n + n)) where r and w are the factors for environmental read and environmental write operations respectively for a reasonable amount of socks. The cost of the logical and arithmetical operations are omitted, because we suppose that it takes a constant amount of logical and arithmetical operations to decide whether 2 socks belong to the same pair. This may not be feasible in every scenario.

Opening a CHM file produces: "navigation to the webpage was canceled"

Win 8 x64:

just move it to another folder or rename your folder (in my case: my folder was "c#"). avoid to use symbol on folder name. name it with letter.

done.

How to remove a package in sublime text 2

If you installed with package control, search for "Package Control: Remove Package" in the command palette (accessed with Ctrl+Shift+P). Otherwise you can just remove the Emmet directory.

If you wish to use a custom caption to access commands, create Default.sublime-commands in your User folder. Then insert something similar to the following.

[
    {
        "caption": "Package Control: Uninstall Package",
        "command": "remove_package"
    }
]

Of course, you can customize the command and caption as you see fit.

How to get last key in an array?

Although end() seems to be the easiest, it's not the fastest. The faster, and much stronger alternative is array_slice():

$lastKey = key(array_slice($array, -1, 1, true));

As the tests say, on an array with 500000 elements, it is almost 7x faster!

Testing if a checkbox is checked with jQuery

You can perform it, this way:

$('input[id=ans]').is(':checked');     

Break or return from Java 8 stream forEach?

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

How to check if a file exists in Ansible?

In general you would do this with the stat module. But the command module has the creates option which makes this very simple:

- name: touch file
  command: touch /etc/file.txt
  args:
    creates: /etc/file.txt

I guess your touch command is just an example? Best practice would be to not check anything at all and let ansible do its job - with the correct module. So if you want to ensure the file exists you would use the file module:

- name: make sure file exists
  file:
    path: /etc/file.txt
    state: touch

How to disable auto-play for local video in iframe

Replace the iframe for this:

<video class="video-fluid z-depth-1" loop controls muted>
  <source src="videos/example.mp4" type="video/mp4" />
</video>

Python "expected an indented block"

This one is wrong at least:

            for x in range(x, 1, 1):
        elif option == 0:

Column/Vertical selection with Keyboard in SublimeText 3

In my case (Linux) is alt+shift up/down

 { "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
 { "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },    

How to change theme for AlertDialog

I have written an article in my blog on how to configure the layout of an AlertDialog with XML style files. The main problem is that you need different style definitions for different layout parameters. Here is a boilerplate based on the AlertDialog style of Holo Light Platform version 19 for a style file that should cover a bunch of the standard layout aspects like text sizes and background colors.

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    ...
    <item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
    <item name="android:alertDialogStyle">@style/MyAlertDialogStyle</item>
    ...
</style>

<style name="MyBorderlessButton">
    <!-- Set background drawable and text size of the buttons here -->
    <item name="android:background">...</item>
    <item name="android:textSize">...</item>
</style>

<style name="MyButtonBar">
    <!-- Define a background for the button bar and a divider between the buttons here -->
    <item name="android:divider">....</item>
    <item name="android:dividerPadding">...</item>
    <item name="android:showDividers">...</item>
    <item name="android:background">...</item>
</style>

<style name="MyAlertDialogTitle">
    <item name="android:maxLines">1</item>
    <item name="android:scrollHorizontally">true</item>
</style>

<style name="MyAlertTextAppearance">
    <!-- Set text size and color of title and message here -->
    <item name="android:textSize"> ... </item>
    <item name="android:textColor">...</item>
</style>

<style name="MyAlertDialogTheme">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowTitleStyle">@style/MyAlertDialogTitle</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
    <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:textAppearanceMedium">@style/MyAlertTextAppearance</item>
    <!-- If you don't want your own button bar style use
            @android:style/Holo.Light.ButtonBar.AlertDialog
            and
            ?android:attr/borderlessButtonStyle
         instead of @style/MyButtonBar and @style/MyBorderlessButton -->
    <item name="android:buttonBarStyle">@style/MyButtonBar</item>
    <item name="android:buttonBarButtonStyle">@style/MyBorderlessButton</item>
</style>

<style name="MyAlertDialogStyle">
    <!-- Define background colors of title, message, buttons, etc. here -->
    <item name="android:fullDark">...</item>
    <item name="android:topDark">...</item>
    <item name="android:centerDark">...</item>
    <item name="android:bottomDark">...</item>
    <item name="android:fullBright">...</item>
    <item name="android:topBright">...</item>
    <item name="android:centerBright">...</item>
    <item name="android:bottomBright">...</item>
    <item name="android:bottomMedium">...</item>
    <item name="android:centerMedium">...</item>
</style>

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

How to push object into an array using AngularJS

A couple of answers that should work above but this is how i would write it.

Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.

add-text.tpl.html

<div ng-controller="myController">
    <form ng-submit="addText(myText)">
        <input type="text" placeholder="Let's Go" ng-model="myText">
        <button type="submit">Add</button>
    </form>
    <ul>
        <li ng-repeat="text in arrayText">{{ text }}</li>
    </ul>
</div>

app.js

(function() {

    function myController($scope) {
        $scope.arrayText = ['hello', 'world'];
        $scope.addText = function(myText) {
             $scope.arrayText.push(myText);     
        };
    }

    angular.module('app', [])
        .controller('myController', myController);

})();

How to remove decimal values from a value of type 'double' in Java

Use Math.Round(double);

I have used it myself. It actually rounds off the decimal places.

d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20 

d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19 

Hope it Helps :-)

ImportError: No Module Named bs4 (BeautifulSoup)

If you use Pycharm, go to preferences - project interpreter - install bs4.

If you try to install BeautifulSoup, it will still show that no module named bs4.

getting "No column was specified for column 2 of 'd'" in sql server cte?

I had a similar query and a similar issue.

SELECT
    *
FROM
    Users ru
    LEFT OUTER JOIN 
    (
        SELECT ru1.UserID, COUNT(*)
        FROM Referral r
        LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
        GROUP BY ru1.UserID
    ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

I found that SQL Server was choking on the COUNT(*) column, and was giving me the error No column was specified for column 2.

Putting an alias on the COUNT(*) column fixed the issue.

  SELECT
        *
    FROM
        Users ru
        LEFT OUTER JOIN 
        (
            SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
            FROM Referral r
            LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
            GROUP BY ru1.UserID
        ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

asp:TextBox ReadOnly=true or Enabled=false?

I have a child aspx form that does an address lookup server side. The values from the child aspx page are then passed back to the parent textboxes via javascript client side.

Although you can see the textboxes have been changed neither ReadOnly or Enabled would allow the values to be posted back in the parent form.

How to check if array is not empty?

if self.table:
    print 'It is not empty'

Is fine too

How to convert numbers to words without using num2word library?

Are you allowed to use other packages? This one works really well for me: Inflect. It is useful for natural language generation and has a method for turning numbers into english text.

I installed it with

$ pip install inflect

Then in your Python session

>>> import inflect
>>> p = inflect.engine()
>>> p.number_to_words(1234567)
'one million, two hundred and thirty-four thousand, five hundred and sixty-seven'

>>> p.number_to_words(22)
'twenty-two'

What is the difference between a static and const variable?

Const means “cannot be changed.”

Static means “static instance (in memory) vs dynamic instance (on the stack.)” Static variables exist for the duration of the program. Dynamic ones are created and destroyed as needed.

A variable can be one or both.

moving committed (but not pushed) changes to a new branch after pull

This should be fine, since you haven't pushed your commits anywhere else yet, and you're free to rewrite the history of your branch after origin/master. First I would run a git fetch origin to make sure that origin/master is up to date. Assuming that you're currently on master, you should be able to do:

git rebase origin/master

... which will replay all of your commits that aren't in origin/master onto origin/master. The default action of rebase is to ignore merge commits (e.g. those that your git pulls probably introduced) and it'll just try to apply the patch introduced by each of your commits onto origin/master. (You may have to resolve some conflicts along the way.) Then you can create your new branch based on the result:

git branch new-work

... and then reset your master back to origin/master:

# Use with care - make sure "git status" is clean and you're still on master:
git reset --hard origin/master

When doing this kind of manipulating branches with git branch, git reset, etc. I find it useful to frequently look at the commit graph with gitk --all or a similar tool, just to check that I understand where all the different refs are pointing.

Alternatively, you could have just created a topic branch based on where your master is at in the first place (git branch new-work-including-merges) and then reset master as above. However, since your topic branch will include merges from origin/master and you've not pushed your changes yet, I'd suggest doing a rebase so that the history is tidier. (Also, when you eventually merge your topic branch back to master, the changes will be more obvious.)

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Delete a database in phpMyAdmin

If you want to delete your database from phpmyAdmin or mySQl. Simply go to SQL command and write command "drop DATABASE databasename;"

Example: drop DATABASE rainbowonlineshopping;

enter image description here

Then click on "Go" Button. Your Database will be deleted and you get information like this

enter image description here

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Unfortunately triggering the onsubmit or submit events wont work in all browsers.

  • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
  • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

<script type="text/javascript">
$(function() {

    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 
        });

    $('form#ajaxForm').find('a.submit-link').click( function() { 
        $'form#ajaxForm').submit();
        });

  }
</script>
  <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
     {
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   Description:
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link">Save</a> 
<% } %>

Also, the link doesn't have to be contained within the form in order for this to work.

Get the current user, within an ApiController action, without passing the userID as a parameter

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Check if argparse optional argument is set or not

I think that optional arguments (specified with --) are initialized to None if they are not supplied. So you can test with is not None. Try the example below:

import argparse as ap

def main():
    parser = ap.ArgumentParser(description="My Script")
    parser.add_argument("--myArg")
    args, leftovers = parser.parse_known_args()

    if args.myArg is not None:
        print "myArg has been set (value is %s)" % args.myArg

What are .NumberFormat Options In Excel VBA?

In Excel, you can set a Range.NumberFormat to any string as you would find in the "Custom" format selection. Essentially, you have two choices:

  1. General for no particular format.
  2. A custom formatted string, like "$#,##0", to specify exactly what format you're using.

How to create jobs in SQL Server Express edition

SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.

There are a few third-party extensions that provide that capability - check out e.g.:

Access files stored on Amazon S3 through web browser

I had the same problem and I fixed it by using the

  1. new context menu "Make Public".
  2. Go to https://console.aws.amazon.com/s3/home,
  3. select the bucket and then for each Folder or File (or multiple selects) right click and
  4. "make public"

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

JavaScript: clone a function

try this:

var x = function() {
    return 1;
};

var t = function(a,b,c) {
    return a+b+c;
};


Function.prototype.clone = function() {
    var that = this;
    var temp = function temporary() { return that.apply(this, arguments); };
    for(var key in this) {
        if (this.hasOwnProperty(key)) {
            temp[key] = this[key];
        }
    }
    return temp;
};

alert(x === x.clone());
alert(x() === x.clone()());

alert(t === t.clone());
alert(t(1,1,1) === t.clone()(1,1,1));
alert(t.clone()(1,1,1));

Change an image with onclick()

You can try something like this:

CSS

div {
    width:200px;
    height:200px;
    background: url(img1.png) center center no-repeat;
}

.visited {
    background: url(img2.png) center center no-repeat;
}

HTML

<div href="#" onclick="this.className='visited'">
    <p>Content</p>
</div>

Fiddle

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

Basic text editor in command prompt?

There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing edit.com.

I hope this helped

Binding a list in @RequestParam

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}

That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

This is the simplest solution :)

Could not find method android() for arguments

This error appear because the compiler could not found "my-upload-key.keystore" file in your project

After you have generated the file you need to paste it into project's andorid/app folder

this worked for me!

VBA Convert String to Date

Try using Replace to see if it will work for you. The problem as I see it which has been mentioned a few times above is the CDate function is choking on the periods. You can use replace to change them to slashes. To answer your question about a Function in vba that can parse any date format, there is not any you have very limited options.

Dim current as Date, highest as Date, result() as Date 
For Each itemDate in DeliveryDateArray
    Dim tempDate As String
    itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
    tempDate = Replace(itemDate, ".", "/")
    current = Format(CDate(tempDate),"dd/mm/yyyy")
    if current > highest then 
        highest = current 
    end if 
    ' some more operations an put dates into result array 
Next itemDate 
'After activating final sheet... 
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result) 

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

Java method to sum any number of ints

 public static void main(String args[])
 {
 System.out.println(SumofAll(12,13,14,15));//Insert your number here.
   {
      public static int SumofAll(int...sum)//Call this method in main method.
          int total=0;//Declare a variable which will hold the total value.
            for(int x:sum)
          {
           total+=sum;
           }
  return total;//And return the total variable.
    }
 }

Find the location of a character in string

You could use grep as well:

grep('2', strsplit(string, '')[[1]])
#4 24

Best way to get application folder path

Note that not all of these methods will return the same value. In some cases, they can return the same value, but be careful, their purposes are different:

Application.StartupPath

returns the StartupPath parameter (can be set when run the application)

System.IO.Directory.GetCurrentDirectory()

returns the current directory, which may or may not be the folder where the application is located. The same goes for Environment.CurrentDirectory. In case you are using this in a DLL file, it will return the path of where the process is running (this is especially true in ASP.NET).

Remove characters from a string

ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

Catch a thread's exception in the caller thread in Python

As a noobie to Threading, it took me a long time to understand how to implement Mateusz Kobos's code (above). Here's a clarified version to help understand how to use it.

#!/usr/bin/env python

import sys
import threading
import Queue

class ExThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__status_queue = Queue.Queue()

    def run_with_exception(self):
        """This method should be overriden."""
        raise NotImplementedError

    def run(self):
        """This method should NOT be overriden."""
        try:
            self.run_with_exception()
        except Exception:
            self.__status_queue.put(sys.exc_info())
        self.__status_queue.put(None)

    def wait_for_exc_info(self):
        return self.__status_queue.get()

    def join_with_exception(self):
        ex_info = self.wait_for_exc_info()
        if ex_info is None:
            return
        else:
            raise ex_info[1]

class MyException(Exception):
    pass

class MyThread(ExThread):
    def __init__(self):
        ExThread.__init__(self)

    # This overrides the "run_with_exception" from class "ExThread"
    # Note, this is where the actual thread to be run lives. The thread
    # to be run could also call a method or be passed in as an object
    def run_with_exception(self):
        # Code will function until the int
        print "sleeping 5 seconds"
        import time
        for i in 1, 2, 3, 4, 5:
            print i
            time.sleep(1) 
        # Thread should break here
        int("str")
# I'm honestly not sure why these appear here? So, I removed them. 
# Perhaps Mateusz can clarify?        
#         thread_name = threading.current_thread().name
#         raise MyException("An error in thread '{}'.".format(thread_name))

if __name__ == '__main__':
    # The code lives in MyThread in this example. So creating the MyThread 
    # object set the code to be run (but does not start it yet)
    t = MyThread()
    # This actually starts the thread
    t.start()
    print
    print ("Notice 't.start()' is considered to have completed, although" 
           " the countdown continues in its new thread. So you code "
           "can tinue into new processing.")
    # Now that the thread is running, the join allows for monitoring of it
    try:
        t.join_with_exception()
    # should be able to be replace "Exception" with specific error (untested)
    except Exception, e: 
        print
        print "Exceptioon was caught and control passed back to the main thread"
        print "Do some handling here...or raise a custom exception "
        thread_name = threading.current_thread().name
        e = ("Caught a MyException in thread: '" + 
             str(thread_name) + 
             "' [" + str(e) + "]")
        raise Exception(e) # Or custom class of exception, such as MyException

How do I specify the JDK for a GlassFish domain?

Adding the actual content from dbf's link in order to keep the solution within stackoverflow.

It turns out that when I first installed Glassfish on my Windows system I had JDK 6 installed, and recently I had to downgrade to JDK 5 to compile some code for another project.

Apparently when Glassfish is installed it hard-codes its reference to your JDK location, so to fix this problem I ended up having to edit a file named asenv.bat. In short, I edited this file:

C:\glassfish\config\asenv.bat:

and I commented out the reference to JDK 6 and added a new reference to JDK 5, like this:

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

Although the path doesn't appear to be case sensitive, I've spent hours debugging an issue around JMS Destination object not found due to my replacement path's case being incorrect.

gcc-arm-linux-gnueabi command not found

You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.

Use an i686 VM.

npm install private github repositories by dependency in package.json

"dependencies": {
  "some-package": "github:github_username/some-package"
}

or just

"dependencies": {
  "some-package": "github_username/some-package"
}

https://docs.npmjs.com/files/package.json#github-urls

Python - Get Yesterday's date as a string in YYYY-MM-DD format

Calling .isoformat() on a date object will give you YYYY-MM-DD

from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()

MySql Query Replace NULL with Empty String in Select

Try below ;

  select if(prereq IS NULL ," ",prereq ) from test

Nested JSON: How to add (push) new items to an object?

If your JSON is without key you can do it like this:

library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

So, try this:

var library = {[{
    "title"       : "Gold Rush",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["1.jpg","","2.jpg"]
    }, {
    "title"       : California",
        "foregrounds" : ["Slide 1","Slide 2","Slide 3"],
        "backgrounds" : ["3.jpg","4.jpg","5.jpg"]
    }]
}

Then:

library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};

Extract part of a regex match

Use ( ) in regexp and group(1) in python to retrieve the captured string (re.search will return None if it doesn't find the result, so don't use group() directly):

title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)

How do I do top 1 in Oracle?

To select the first row from a table and to select one row from a table are two different tasks and need a different query. There are many possible ways to do so. Four of them are:

First

select  max(Fname) from MyTbl;

Second

select  min(Fname) from MyTbl;

Third

select  Fname from MyTbl  where rownum = 1;

Fourth

select  max(Fname) from MyTbl where rowid=(select  max(rowid) from MyTbl)

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

Call of overloaded function is ambiguous

Use

p.setval(static_cast<const char *>(0));

or

p.setval(static_cast<unsigned int>(0));

As indicated by the error, the type of 0 is int. This can just as easily be cast to an unsigned int or a const char *. By making the cast manually, you are telling the compiler which overload you want.

set option "selected" attribute from dynamic created option

You're overthinking it:

var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;

How to read a file without newlines?

another example:

Reading file one row at the time. Removing unwanted chars with from end of the string str.rstrip(chars)

with open(filename, 'r') as fileobj:
    for row in fileobj:
        print( row.rstrip('\n') )

see also str.strip([chars]) and str.lstrip([chars])

(python >= 2.0)

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

Can you autoplay HTML5 videos on the iPad?

As of iOS 10, videos now can autoplay, but only of they are either muted, or have no audio track. Yay!

In short:

  • <video autoplay> elements will now honor the autoplay attribute, for elements which meet the following conditions:
    • <video> elements will be allowed to autoplay without a user gesture if their source media contains no audio tracks.
    • <video muted> elements will also be allowed to autoplay without a user gesture.
    • If a <video> element gains an audio track or becomes un-muted without a user gesture, playback will pause.
    • <video autoplay> elements will only begin playing when visible on-screen such as when they are scrolled into the viewport, made visible through CSS, and inserted into the DOM.
    • <video autoplay> elements will pause if they become non-visible, such as by being scrolled out of the viewport.

More info here: https://webkit.org/blog/6784/new-video-policies-for-ios/

How to check if a String contains any letter from a to z?

For a minimal change:

for(int i=0; i<str.Length; i++ )
   if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
      errorCount++;

You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.

How to get value of Radio Buttons?

You can also use a Common Event for your RadioButtons, and you can use the Tag property to pass information to your string or you can use the Text Property if you want your string to hold the same value as the Text of your RadioButton.

Something like this.

private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    if (((RadioButton)sender).Checked == true)
        sex = ((RadioButton)sender).Tag.ToString();
}

Reference an Element in a List of Tuples

You can get a list of the first element in each tuple using a list comprehension:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']

How do I remove the old history from a git repository?

Try this method How to truncate git history :

#!/bin/bash
git checkout --orphan temp $1
git commit -m "Truncated history"
git rebase --onto temp $1 master
git branch -D temp

Here $1 is SHA-1 of the commit you want to keep and the script will create new branch that contains all commits between $1 and master and all the older history is dropped. Note that this simple script assumes that you do not have existing branch called temp. Also note that this script does not clear the git data for old history. Run git gc --prune=all && git repack -a -f -F -d after you've verified that you truly want to lose all history. You may also need rebase --preserve-merges but be warned that the git implementation of that feature is not perfect. Inspect the results manually if you use that.

Add spaces between the characters of a string in Java?

I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break) and \u00A0 (for spacing) or alternatively $#032

AngularJS $http-post - convert binary to excel file and download

You could as well take an alternative approach -- you don't have to use $http, you don't need any extra libraries, and it ought to work in any browser.

Just place an invisible form on your page.

<form name="downloadForm" action="/MyApp/MyFiles/Download" method="post" target="_self">
    <input type="hidden" name="value1" value="{{ctrl.value1}}" />
    <input type="hidden" name="value2" value="{{ctrl.value2}}" />
</form>

And place this code in your angular controller.

ctrl.value1 = 'some value 1';  
ctrl.value2 = 'some value 2';  
$timeout(function () {
    $window.document.forms['downloadForm'].submit();
});

This code will post your data to /MyApp/MyFiles/Download and you'll receive a file in your Downloads folder.
It works with Internet Explorer 10.

If a conventional HTML form doesn't let you post your complex object, then you have two options:

1. Stringify your object and put it into one of the form fields as a string.

<input type="hidden" name="myObjJson" value="{{ctrl.myObj | json:0}}" />


2. Consider HTML JSON forms: https://www.w3.org/TR/html-json-forms/

Android Design Support Library expandable Floating Action Button(FAB) menu

Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.

Just using animate().translationY() function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.

first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:

    <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab3"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_btn_speak_now" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab2"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_menu_camera" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab1"
    android:layout_width="@dimen/standard_45"
    android:layout_height="@dimen/standard_45"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_21"
    app:srcCompat="@android:drawable/ic_dialog_map" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_dialog_email" />

Now in your java class just define all your FAB and perform the click like shown below:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab1 = (FloatingActionButton) findViewById(R.id.fab1);
    fab2 = (FloatingActionButton) findViewById(R.id.fab2);
    fab3 = (FloatingActionButton) findViewById(R.id.fab3);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!isFABOpen){
                showFABMenu();
            }else{
                closeFABMenu();
            }
        }
    });

Use the animation().translationY() to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:

 private void showFABMenu(){
    isFABOpen=true;
    fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
    fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
    fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}

private void closeFABMenu(){
    isFABOpen=false;
    fab1.animate().translationY(0);
    fab2.animate().translationY(0);
    fab3.animate().translationY(0);
}

Now define the above mentioned dimension inside res->values->dimens.xml as shown below:

    <dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>

That's all hope this solution will help the people in future, who are searching for simple solution.

EDITED

If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github

to close the FAB on Backpress, override onBackPress() as showen below:

    @Override
public void onBackPressed() {
    if(!isFABOpen){
        this.super.onBackPressed();
    }else{
        closeFABMenu();
    }
}

The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub

enter image description here

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

How do I activate C++ 11 in CMake?

OS X and Homebrew LLVM related:

Don't forget to call cmake_minimum_required(VERSION 3.3) and project() after it!

Or CMake will insert project() implicitly before line 1, causing trouble with Clang version detection and possibly other sorts of troubles. Here is a related issue.

How do I register a .NET DLL file in the GAC?

  • Run Developer Command Prompt For V2012 or any version installed in your system

  • gacutil /i pathofDll

  • Enter

Done!!!

Comparing two strings, ignoring case in C#

The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.

How to extract public key using OpenSSL?

If your looking how to copy an Amazon AWS .pem keypair into a different region do the following:

openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub

Then

aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. The insert or update statement is correct. And I also checked the encoding. The column does exist. Then! I found out that I was referencing the column in my Trigger. You should also check your trigger see if any script is referencing the column you are having the problem with.

How do I split a string on a delimiter in Bash?

There is a simple and smart way like this:

echo "add:sfff" | xargs -d: -i  echo {}

But you must use gnu xargs, BSD xargs cant support -d delim. If you use apple mac like me. You can install gnu xargs :

brew install findutils

then

echo "add:sfff" | gxargs -d: -i  echo {}

Genymotion Android emulator - adb access?

Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands

Running Node.Js on Android

J2V8 is best solution of your problem. It's run Nodejs application on jvm(java and android).

J2V8 is Java Bindings for V8, But Node.js integration is available in J2V8 (version 4.4.0)

Github : https://github.com/eclipsesource/J2V8

Example : http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/

Giving my function access to outside variable

The one and probably not so good way of achieving your goal would using global variables.

You could achieve that by adding global $myArr; to the beginning of your function. However note that using global variables is in most cases a bad idea and probably avoidable.

The much better way would be passing your array as an argument to your function:

function someFuntion($arr){
    $myVal = //some processing here to determine value of $myVal
    $arr[] = $myVal;
    return $arr;
}

$myArr = someFunction($myArr);

how to generate web service out of wsdl

You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good.

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

How to redirect from one URL to another URL?

window.location.href = "URL2"

inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.

What is the difference between functional and non-functional requirements?

Functional requirements are those which are related to the technical functionality of the system.

non-functional requirement is a requirement that specifies criteria that can be used to judge the operation of a system in particular conditions, rather than specific behaviors.

For example if you consider a shopping site, adding items to cart, browsing different items, applying offers and deals and successfully placing orders comes under functional requirements.

Where as performance of the system in peak hours, time taken for the system to retrieve data from DB, security of the user data, ability of the system to handle if large number of users login comes under non functional requirements.

Class method differences in Python: bound, unbound and static

The definition of method_two is invalid. When you call method_two, you'll get TypeError: method_two() takes 0 positional arguments but 1 was given from the interpreter.

An instance method is a bounded function when you call it like a_test.method_two(). It automatically accepts self, which points to an instance of Test, as its first parameter. Through the self parameter, an instance method can freely access attributes and modify them on the same object.

Is bool a native C type?

stdbool.h defines macros true and false, but remember they are defined to be 1 and 0.

That is why sizeof(true) is 4.

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

Convert a matrix to a 1 dimensional array

Simple and fast since a 1d array is essentially a vector

vector <- array[1:length(array)]

Python Unicode Encode Error

Excellent post : http://www.carlosble.com/2010/12/understanding-python-and-unicode/

# -*- coding: utf-8 -*-

def __if_number_get_string(number):
    converted_str = number
    if isinstance(number, int) or \
            isinstance(number, float):
        converted_str = str(number)
    return converted_str


def get_unicode(strOrUnicode, encoding='utf-8'):
    strOrUnicode = __if_number_get_string(strOrUnicode)
    if isinstance(strOrUnicode, unicode):
        return strOrUnicode
    return unicode(strOrUnicode, encoding, errors='ignore')


def get_string(strOrUnicode, encoding='utf-8'):
    strOrUnicode = __if_number_get_string(strOrUnicode)
    if isinstance(strOrUnicode, unicode):
        return strOrUnicode.encode(encoding)
    return strOrUnicode

jQuery validation: change default error message

This worked for me:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

VSCode single to double quote automatic replace

There only solution that worked for me: and only for Angular Projects:

Just go into your project ".editorconfig" file and paste 'quote_type = single'. Hope it should work for you as well.

How to bind Dataset to DataGridView in windows application

use like this :-

gridview1.DataSource = ds.Tables[0]; <-- Use index or your table name which you want to bind
gridview1.DataBind();

I hope it helps!!

Limit to 2 decimal places with a simple pipe

Well now will be different after angular 5:

{{ number | currency :'GBP':'symbol':'1.2-2' }}

npm install gives error "can't find a package.json file"

solve using this code:

npm install npm@latest -g

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

"Operation must use an updateable query" error in MS Access

I had the same error when was trying to update linked table.

The issue was that linked table had no PRIMARY KEY.

After adding primary key constraint on database side and re linking this table to access problem was solved.

Hope it will help somebody.

Where does application data file actually stored on android device?

You can get if from your document_cache folder, subfolder (mine is 1946507). Once there, rename the "content" by adding .pdf to the end of the file, save, and open with any pdf reader.

glm rotate usage in Opengl

I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)) you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z)) instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))

Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

You can add glm::radians() if you want to keep using degrees. And add the includes:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

What is "not assignable to parameter of type never" error in typescript?

All you have to do is define your result as a string array, like the following:

const result : string[] = [];

Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.

How to Import .bson file format on mongodb

I have used this:

mongorestore -d databasename -c file.bson fullpath/file.bson

1.copy the file path and file name from properties (try to put all bson files in different folder), 2.use this again and again with changing file name only.

html/css buttons that scroll down to different div sections on a webpage

For something really basic use this:

<a href="#middle">Go To Middle</a>

Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.

How do I calculate a trendline for a graph?

Regarding a previous answer

if (B) y = offset + slope*x

then (C) offset = y/(slope*x) is wrong

(C) should be:

offset = y-(slope*x)

See: http://zedgraph.org/wiki/index.php?title=Trend

How do you pass a function as a parameter in C?

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22

Microsoft.Office.Core Reference Missing

If someone not have reference in .NET . COM (tab) or not have office installed on machine where visual was installed can do :

  1. Download and install: Microsoft Office Developer Tools
  2. Add references from:

    C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15
    

Call method when home button pressed

I have a simple solution on handling home button press. Here is my code, it can be useful:

public class LifeCycleActivity extends Activity {


boolean activitySwitchFlag = false;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        activitySwitchFlag = true;
        // activity switch stuff..
        return true;
    }
    return false;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override 
public void onPause(){
    super.onPause();
    Log.v("TAG", "onPause" );
    if(activitySwitchFlag)
        Log.v("TAG", "activity switch");
    else
        Log.v("TAG", "home button");
    activitySwitchFlag = false;
}

public void gotoNext(View view){
    activitySwitchFlag = true;
    startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}

}

As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..

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

All you have to do is copy the cv2.pyd file from the x86 folder (C:\opencv\build\python\2.7\x86\ for example) to C:\Python27\Lib\site-packages\ , not from the x64 folder.

Hope that help you.

How to add an image to a JPanel?

JPanel is almost always the wrong class to subclass. Why wouldn't you subclass JComponent?

There is a slight problem with ImageIcon in that the constructor blocks reading the image. Not really a problem when loading from the application jar, but maybe if you're potentially reading over a network connection. There's plenty of AWT-era examples of using MediaTracker, ImageObserver and friends, even in the JDK demos.

What is the purpose of .PHONY in a Makefile?

Let's assume you have install target, which is a very common in makefiles. If you do not use .PHONY, and a file named install exists in the same directory as the Makefile, then make install will do nothing. This is because Make interprets the rule to mean "execute such-and-such recipe to create the file named install". Since the file is already there, and its dependencies didn't change, nothing will be done.

However if you make the install target PHONY, it will tell the make tool that the target is fictional, and that make should not expect it to create the actual file. Hence it will not check whether the install file exists, meaning: a) its behavior will not be altered if the file does exist and b) extra stat() will not be called.

Generally all targets in your Makefile which do not produce an output file with the same name as the target name should be PHONY. This typically includes all, install, clean, distclean, and so on.

How do you fade in/out a background color using jquery?

Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'}) to change the color.

As others have written, some of this can be done using the jQuery UI library as well.

Install a Python package into a different directory using pip?

I suggest to follow the documentation and create ~/.pip/pip.conf file. Note in the documentation there are missing specified header directory, which leads to following error:

error: install-base or install-platbase supplied, but installation scheme is incomplete

The full working content of conf file is:

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data

Unfortunatelly I can install, but when try to uninstall pip tells me there is no such package for uninstallation process.... so something is still wrong but the package goes to its predefined location.

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

A different installation of ruby should be used. I use rbenv for that purpose.

# install your version of ruby
$ rbenv install 2.0.0-p247

# modify .ruby_version on current directory
$ rbenv local 2.0.0-p247

# proceed installing gems
$ gem install bundler

Disclamer: I am not a ruby person. This worked for me and if you are a ruby expert and see things to change in this answer, please, go ahead or comment!

Get current category ID of the active page

You can try using get_the_category():

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;

Rounding up to next power of 2

import sys


def is_power2(x):
    return x > 0 and ((x & (x - 1)) == 0)


def find_nearest_power2(x):
    if x <= 0:
        raise ValueError("invalid input")
    if is_power2(x):
        return x
    else:
        bits = get_bits(x)
        upper = 1 << (bits)
        lower = 1 << (bits - 1)
        mid = (upper + lower) // 2
        if (x - mid) > 0:
            return upper
        else:
            return lower


def get_bits(x):
    """return number of bits in binary representation"""
    if x < 0:
        raise ValueError("invalid input: input should be positive integer")
    count = 0
    while (x != 0):
        try:
            x = x >> 1
        except TypeError as error:
            print(error, "input should be of type integer")
            sys.exit(1)
        count += 1
    return count

Question mark and colon in JavaScript

This is probably a bit clearer when written with brackets as follows:

hsb.s = (max != 0) ? (255 * delta / max) : 0;

What it does is evaluate the part in the first brackets. If the result is true then the part after the ? and before the : is returned. If it is false, then what follows the : is returned.

Regex pattern to match at least 1 number and 1 character in a string

Maybe a bit late, but this is my RE:

/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/

Explanation:

\w* -> 0 or more alphanumeric digits, at the beginning

\d+[a-zA-Z]|[a-zA-Z]+\d -> a digit + a letter OR a letter + a digit

\w* -> 0 or more alphanumeric digits, again

I hope it was understandable

Phone number formatting an EditText in Android

Follow the instructions in this Answer to format the EditText mask.

https://stackoverflow.com/a/34907607/1013929

And after that, you can catch the original numbers from the masked string with:

String phoneNumbers = maskedString.replaceAll("[^\\d]", "");

How to check if a character is upper-case in Python?

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

So you can write it in 1 string

Finding the max value of an attribute in an array of objects

Comparison of three ONELINERS which handle minus numbers case (input in a array):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

_x000D_
_x000D_
var a = [
  {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
  {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;

document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
_x000D_
_x000D_

For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

_x000D_
_x000D_
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }

try {
  let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
_x000D_
_x000D_

Benchmark for the 4 element array

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Just do this

<button OnClick=" location.href='link.html' ">Visit Page Now</button>

Although, it's been a while since I've touched JavaScript - maybe location.href is outdated? Anyways, that's how I would do it.

Best way in asp.net to force https for an entire site?

-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.

-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.

Which forces your entire application to HTTPS.

How to write unit testing for Angular / TypeScript for private methods with Jasmine

This route I take is one where I create functions outside the class and assign the function to my private method.

export class MyClass {
  private _myPrivateFunction = someFunctionThatCanBeTested;
}

function someFunctionThatCanBeTested() {
  //This Is Testable
}

Now I don't know what type of OOP rules I am breaking, but to answer the question, this is how I test private methods. I welcome anyone to advise on Pros & Cons of this.

Fail to create Android virtual Device, "No system image installed for this Target"

I had android sdk and android studio installed separately in my system. Android studio had installed its own sdk. After I deleted the stand-alone android sdk, the issue of "“No system image installed for this Target” was gone.

Vuejs: Event on route change

Setup a watcher on the $route in your component like this:

watch:{
    $route (to, from){
        this.show = false;
    }
} 

This observes for route changes and when changed ,sets show to false

How to select all rows which have same value in some column

How about

SELECT *
FROM Employees
WHERE PhoneNumber IN (
    SELECT PhoneNumber
    FROM Employees
    GROUP BY PhoneNumber
    HAVING COUNT(Employee_ID) > 1
    )

SQL Fiddle DEMO

How can I make a weak protocol reference in 'pure' Swift (without @objc)

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }

How to check if a Constraint exists in Sql server?

Just something to watch out for......

In SQL Server 2008 R2 SSMS, the "Script Constraint as -> DROP And CREATE To" command produces T-SQL like below

USE [MyDatabase]
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DEF_Detail_IsDeleted]') AND type = 'D')
BEGIN
ALTER TABLE [Patient].[Detail] DROP CONSTRAINT [DEF_Detail_IsDeleted]
END

GO

USE [MyDatabase]
GO

ALTER TABLE [Patient].[Detail] ADD  CONSTRAINT [DEF_Detail_IsDeleted]  DEFAULT ((0)) FOR [IsDeleted]
GO

Out of the box, this script does NOT drop the constraint because the SELECT returns 0 rows. (see post Microsoft Connect).

The name of the default constraint is wrong but I gather it also has something to do with the OBJECT_ID function because changing the name doesn't fix the problem.

To fix this, I removed the usage of OBJECT_ID and used the default constraint name instead.

(SELECT * FROM dbo.sysobjects WHERE [name] = (N'DEF_Detail_IsDeleted') AND type = 'D')

Hashing a dictionary?

Using sorted(d.items()) isn't enough to get us a stable repr. Some of the values in d could be dictionaries too, and their keys will still come out in an arbitrary order. As long as all the keys are strings, I prefer to use:

json.dumps(d, sort_keys=True)

That said, if the hashes need to be stable across different machines or Python versions, I'm not certain that this is bulletproof. You might want to add the separators and ensure_ascii arguments to protect yourself from any changes to the defaults there. I'd appreciate comments.

How to concatenate string variables in Bash

$ a=hip
$ b=hop
$ ab=$a$b
$ echo $ab
hiphop
$ echo $a$b
hiphop

Modelling an elevator using Object-Oriented Analysis and Design

First there is an elevator class. It has a direction (up, down, stand, maintenance), a current floor and a list of floor requests sorted in the direction. It receives request from this elevator.

Then there is a bank. It contains the elevators and receives the requests from the floors. These are scheduled to all active elevators (not in maintenance).

The scheduling will be like:

  • if available pick a standing elevator for this floor.
  • else pick an elevator moving to this floor.
  • else pick a standing elevator on an other floor.
  • else pick the elevator with the lowest load.

Each elevator has a set of states.

  • Maintenance: the elevator does not react to external signals (only to its own signals).
  • Stand: the elevator is fixed on a floor. If it receives a call. And the elevator is on that floor, the doors open. If it is on another floor, it moves in that direction.
  • Up: the elevator moves up. Each time it reaches a floor, it checks if it needs to stop. If so it stops and opens the doors. It waits for a certain amount of time and closes the door (unless someting is moving through them. Then it removes the floor from the request list and checks if there is another request. If so the elevator starts moving again. If not it enters the state stand.
  • Down: like up but in reverse direction.

There are additional signals:

  • alarm. The elevator stops. And if it is on a floor, the doors open, the request list is cleared, the requests moved back to the bank.
  • door open. Opens the doors if an elevator is on a floor and not moving.
  • door closes. Closed the door if they are open.

EDIT: Some elevators don't start at bottom/first_floor esp. in case of skyscrapers.

min_floor & max_floor are two additional attributes for Elevator.

Iterating through list of list in Python

if you don't want recursion you could try:

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
    for i in layer1:
        if isinstance(i,list):
            for j in i:
                layer2.append(j)
        else:
            print i
    layer1[:]=layer2
    layer2=[]
    if len(layer1)==0:
        break

which gives:

sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one

(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)

Converting a JS object to an array using jQuery

If you know the maximum index in you object you can do the following:

_x000D_
_x000D_
var myObj = {_x000D_
    1: ['c', 'd'],_x000D_
    2: ['a', 'b']_x000D_
  },_x000D_
  myArr;_x000D_
_x000D_
myObj.length = 3; //max index + 1_x000D_
myArr = Array.prototype.slice.apply(myObj);_x000D_
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
_x000D_
_x000D_
_x000D_

How do I delete specific characters from a particular String in Java?

You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.

In some cases a StringBuffer might help you instead.

Use Fieldset Legend with bootstrap

In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:

<fieldset class="border p-2">
   <legend  class="w-auto">Your Legend</legend>
</fieldset>

which looks like this: bootstrap 4 fieldset and legend

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of 10.1.1.2 is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

Send email with PHP from html form on submit with the same script

Here are the PHP mail settings I use:

//Mail sending function
$subject = $_POST['name'];
$to = $_POST['email'];
$from = "[email protected]";

//data
$msg = "Your MSG <br>\n";       

//Headers
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: <".$from. ">" ;

mail($to,$subject,$msg,$headers);
echo "Mail Sent.";

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server.
So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

How to replace NaN value with zero in a huge data frame?

It would seem that is.nan doesn't actually have a method for data frames, unlike is.na. So, let's fix that!

is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))

data123[is.nan(data123)] <- 0

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

How to have multiple CSS transitions on an element?

If you make all the properties animated the same, you can set each separately which will allow you to not repeat the code.

 transition: all 2s;
 transition-property: color, text-shadow;

There is more about it here: CSS transition shorthand with multiple properties?

I would avoid using the property all (transition-property overwrites 'all'), since you could end up with unwanted behavior and unexpected performance hits.

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);