Programs & Examples On #Digest authentication

A challenge-response authentication mechanism for HTTP

What is the difference between Digest and Basic Authentication?

Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.

Digest Access Authentication uses the hashing methodologies to generate the cryptographic result

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

Mergesort with Python

As already said, l.pop(0) is a O(len(l)) operation and must be avoided, the above msort function is O(n**2). If efficiency matter, indexing is better but have cost too. The for x in l is faster but not easy to implement for mergesort : iter can be used instead here. Finally, checking i < len(l) is made twice because tested again when accessing the element : the exception mechanism (try except) is better and give a last improvement of 30% .

def msort(l):
    if len(l)>1:
        t=len(l)//2
        it1=iter(msort(l[:t]));x1=next(it1)
        it2=iter(msort(l[t:]));x2=next(it2)
        l=[]
        try:
            while True:
                if x1<=x2: l.append(x1);x1=next(it1)
                else     : l.append(x2);x2=next(it2)
        except:
            if x1<=x2: l.append(x2);l.extend(it2)
            else:      l.append(x1);l.extend(it1)
    return l

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118

This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

How to copy directories with spaces in the name

robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

Calling a Variable from another Class

class Program
{
    Variable va = new Variable();
    static void Main(string[] args)
    {
        va.name = "Stackoverflow";
    }
}

Using jQuery To Get Size of Viewport

To get size of viewport on load and on resize (based on SimaWB response):

function getViewport() {
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
    $('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}

getViewport();

$(window).resize(function() {
    getViewport()
});

catching stdout in realtime from subprocess

On Linux, I had the same problem of getting rid of the buffering. I finally used "stdbuf -o0" (or, unbuffer from expect) to get rid of the PIPE buffering.

proc = Popen(['stdbuf', '-o0'] + cmd, stdout=PIPE, stderr=PIPE)
stdout = proc.stdout

I could then use select.select on stdout.

See also https://unix.stackexchange.com/questions/25372/

Add line break to 'git commit -m' from the command line

I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...

Only this is needed:

git commit

How to unload a package without restarting R

You can also use the unloadNamespace command, as in:

unloadNamespace("sqldf")

The function detaches the namespace prior to unloading it.

SQL Server: Difference between PARTITION BY and GROUP BY

Suppose we have 14 records of name column in table

in group by

select name,count(*) as totalcount from person where name='Please fill out' group BY name;

it will give count in single row i.e 14

but in partition by

select row_number() over (partition by name) as total from person where name = 'Please fill out';

it will 14 rows of increase in count

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won't need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !

Convert String to double in Java

Try this, BigDecimal bdVal = new BigDecimal(str);

If you want Double only then try Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

Is it possible to disable scrolling on a ViewPager

In my case of using ViewPager 2 alpha 2 the below snippet works

viewPager.isUserInputEnabled = false

Ability to disable user input (setUserInputEnabled, isUserInputEnabled)

refer to this for more changes in viewpager2 1.0.0-alpha02

Also some changes were made latest version ViewPager 2 alpha 4

orientation and isUserScrollable attributes are no longer part of SavedState

refer to this for more changes in viewpager2#1.0.0-alpha04

Address already in use: JVM_Bind java

Is it possible that MySql listening on the same port as JBoss?

Is there a port number given in the error message - something like Address already in use: JVM_Bind:8080

You can change the port in JBoss server.xml to test this.

Function is not defined - uncaught referenceerror

Your issue here is that you're not understanding the scope that you're setting.

You are passing the ready function a function itself. Within this function, you're creating another function called codeAddress. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).

For example:

var myfunction = function(){
    var myVar = 12345;
};

console.log(myVar); // 'undefined' - since it is within 
                    // the scope of the function only.

Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress method available to all:

$(function(){
    $("#imgid").click(function(){
        var address = $("#formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             map.setCenter(results[0].geometry.location);
           }
        });
    });  
});

(You should remove the existing onclick and add an ID to the image element that you want to handle)

Note that I've replaced $(document).ready() with its shortcut of just $() (http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById with the jQuery object.

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

Create a view with ORDER BY clause

use Procedure

Create proc MyView as begin SELECT TOP 99999999999999 Column1, Column2 FROM dbo.Table Order by Column1 end

execute procedure

exec MyView

WCF error: The caller was not authenticated by the service

set anonymous access in your virtual directory

write following credentials to your service

ADTService.ServiceClient adtService = new ADTService.ServiceClient();
adtService.ClientCredentials.Windows.ClientCredential.UserName="windowsuseraccountname";
adtService.ClientCredentials.Windows.ClientCredential.Password="windowsuseraccountpassword";
adtService.ClientCredentials.Windows.ClientCredential.Domain="windowspcname";

after that you call your webservice methods.

Python: Figure out local timezone

In Python 3.x, local timezone can be figured out like this:

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

It's a tricky use of datetime's code .

For python >= 3.6, you'll need

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo

How do I query for all dates greater than a certain date in SQL Server?

To sum it all up, the correct answer is :

select * from db where Date >= '20100401'  (Format of date yyyymmdd)

This will avoid any problem with other language systems and will use the index.

How to convert 1 to true or 0 to false upon model fetch

Use a double not:

!!1 = true;

!!0 = false;

obj.isChecked = !!parseInt(obj.isChecked);

How to send email via Django?

Send the email to a real SMTP server. If you don't want to set up your own then you can find companies that will run one for you, such as Google themselves.

How to exit when back button is pressed?

In my Home Activity I override the "onBackPressed" to:

@Override
public void onBackPressed() {
   Intent intent = new Intent(Intent.ACTION_MAIN);
   intent.addCategory(Intent.CATEGORY_HOME);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
 }

so if the user is in the home activity and press back, he goes to the home screen.

I took the code from Going to home screen Programmatically

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

Are there any free Xml Diff/Merge tools available?

I recommend you to use CodeCompare tool. It supports native highlighting of XML-data and it can be a good solution for your task.

How to convert hex strings to byte values in Java

You can try something similar to this :

String s = "65";

byte value = Byte.valueOf(s);

Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.

How to Generate Unique Public and Private Key via RSA

The RSACryptoServiceProvider(CspParameters) constructor creates a keypair which is stored in the keystore on the local machine. If you already have a keypair with the specified name, it uses the existing keypair.

It sounds as if you are not interested in having the key stored on the machine.

So use the RSACryptoServiceProvider(Int32) constructor:

public static void AssignNewKey(){
    RSA rsa = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

EDIT:

Alternatively try setting the PersistKeyInCsp to false:

public static void AssignNewKey(){
    const int PROVIDER_RSA_FULL = 1;
    const string CONTAINER_NAME = "KeyContainer";
    CspParameters cspParams;
    cspParams = new CspParameters(PROVIDER_RSA_FULL);
    cspParams.KeyContainerName = CONTAINER_NAME;
    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
    cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
    rsa = new RSACryptoServiceProvider(cspParams);

    rsa.PersistKeyInCsp = false;

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

Select from where field not equal to Mysql Php

You can use also

select * from tablename where column1 ='a' and column2!='b';

            

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Via SQL as per MSDN

SET IDENTITY_INSERT sometableWithIdentity ON

INSERT INTO sometableWithIdentity 
    (IdentityColumn, col2, col3, ...)
VALUES 
    (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF

The complete error message tells you exactly what is wrong...

Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I'd try something like:

#!/usr/bin/python
from __future__ import print_function

import shlex
from subprocess import Popen, PIPE

def shlep(cmd):
    '''shlex split and popen
    '''
    parsed_cmd = shlex.split(cmd)
    ## if parsed_cmd[0] not in approved_commands:
    ##    raise ValueError, "Bad User!  No output for you!"
    proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    return (proc.returncode, out, err)

... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.

Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.

Is it possible to get the current spark context settings in PySpark?

For Spark 2+ you can also use when using scala

spark.conf.getAll; //spark as spark session 

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

CORS with POSTMAN

If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).

Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.

Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.

How to search multiple columns in MySQL?

If it is just for searching then you may be able to use CONCATENATE_WS. This would allow wild card searching. There may be performance issues depending on the size of the table.

SELECT * 
FROM pages 
WHERE CONCAT_WS('', column1, column2, column3) LIKE '%keyword%'

Display an image into windows forms

private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb = new PictureBox();
        pb.Location = new Point(0, 0);
        pb.Size = new Size(150, 150);
        pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
        pb.Visible = true;
        this.Controls.Add(pb);
    }

Extract a substring using PowerShell

Building on Matt's answer, here's one that searches across newlines and is easy to modify for your own use

$String="----start----`nHello World`n----end----"
$SearchStart="----start----`n" #Will not be included in results
$SearchEnd="`n----end----" #Will not be included in results
$String -match "(?s)$SearchStart(?<content>.*)$SearchEnd"
$result=$matches['content']
$result

--

NOTE: if you want to run this against a file keep in mind Get-Content returns an array not a single string. You can work around this by doing the following:

$String=[string]::join("`n", (Get-Content $Filename))

How to Display Selected Item in Bootstrap Button Dropdown Title

Further modified based on answer from @Kyle as $.text() returns exact string, so the caret tag is printed literally, than as a markup, just in case someone would like to keep the caret intact in dropdown.

$(".dropdown-menu li").click(function(){
  $(this).parents(".btn-group").find('.btn').html(
  $(this).text()+" <span class=\"caret\"></span>"
  );
});

Difference between frontend, backend, and middleware in web development

Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works

Scroll Element into View with Selenium

In most of the situation for scrolling this code will work.

WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
js.executeScript("arguments[0].click();",element);

Setting the height of a SELECT in IE

Not sure but I think this was a question not about the height of a 'multiple' type of select element but a drop-down type of select element. I have come across times when the drop-down looks squashed and does not show clearly the selected value. Undoubtedly it has to do with CSS style info in use on the page. The only way to stop it is either change the CSS (which would likely affect the whole page or parts of it in ways you don't want affected) or use style info in the select element itself to override the CSS that's clobbering it. Example:

<select name="myselect" id="myselect" style="font-size:15px; height:30px">
<option value="someval">somedescr</option>
...
</select>

Hope this helps.

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Interestingly, base R aggregate's data.frame method is not showcased here, above the formula interface is used, so for completeness:

aggregate(
  x = df1[c("x1", "x2")],
  by = df1[c("year", "month")],
  FUN = sum, na.rm = TRUE
)

More generic use of aggregate's data.frame method:

Since we are providing a

  • data.frame as x and
  • a list (data.frame is also a list) as by, this is very useful if we need to use it in a dynamic manner, e.g. using other columns to be aggregated and to aggregate by is very simple
  • also with custom-made aggregation functions

For example like so:

colsToAggregate <- c("x1")
aggregateBy <- c("year", "month")
dummyaggfun <- function(v, na.rm = TRUE) {
  c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
}

aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)

remove url parameters with javascript or jquery

Use this function:

_x000D_
_x000D_
var getCleanUrl = function(url) {_x000D_
  return url.replace(/#.*$/, '').replace(/\?.*$/, '');_x000D_
};_x000D_
_x000D_
// get rid of hash and params_x000D_
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
_x000D_
_x000D_
_x000D_

If you want all the href parts, use this:

_x000D_
_x000D_
var url = document.createElement('a');_x000D_
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';_x000D_
_x000D_
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container_x000D_
console.log(url.protocol); // https:_x000D_
console.log(url.host); // developer.mozilla.org_x000D_
console.log(url.hostname); // developer.mozilla.org_x000D_
console.log(url.port); // (blank - https assumes port 443)_x000D_
console.log(url.pathname); // /en-US/search_x000D_
console.log(url.search); // ?q=URL_x000D_
console.log(url.hash); // #search-results-close-container_x000D_
console.log(url.origin); // https://developer.mozilla.org
_x000D_
_x000D_
_x000D_

In javascript, how do you search an array for a substring match

For a fascinating examination of some of the alternatives and their efficiency, see John Resig's recent posts:

(The problem discussed there is slightly different, with the haystack elements being prefixes of the needle and not the other way around, but most solutions are easy to adapt.)

PHP Checking if the current date is before or after a set date

a MySQL-only solution would be something like this:

SELECT IF (UNIX_TIMESTAMP(`field`) > UNIX_TIMESTAMP(), `field`,'GO AHEAD') as `yourdate`
FROM `table`

In Excel, sum all values in one column in each row where another column is a specific value

You could do this using SUMIF. This allows you to SUM a value in a cell IF a value in another cell meets the specified criteria. Here's an example:

 -   A         B
 1   100       YES
 2   100       YES
 3   100       NO

Using the formula: =SUMIF(B1:B3, "YES", A1:A3), you will get the result of 200.

Here's a screenshot of a working example I just did in Excel:

Excel SUMIF Example

C++ - Assigning null to a std::string

Literal 0 is of type int and you can't assign int to std::string. Use mValue.clear() or assign an empty string mValue="".

Writing Python lists to columns in csv

I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.

 writer.writerow(("ColName1", "ColName2", "ColName"))
                 for i in range(len(first_col_list)):
                     writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))

How to convert a byte array to its numeric value (Java)?

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

For each row in an R dataframe

Well, since you asked for R equivalent to other languages, I tried to do this. Seems to work though I haven't really looked at which technique is more efficient in R.

> myDf <- head(iris)
> myDf
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> nRowsDf <- nrow(myDf)
> for(i in 1:nRowsDf){
+ print(myDf[i,4])
+ }
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.4

For the categorical columns though, it would fetch you a Data Frame which you could typecast using as.character() if needed.

relative path in BAT script

Use this in your batch file:

%~dp0\bin\Iris.exe

%~dp0 resolves to the full path of the folder in which the batch script resides.

Deploying my application at the root in Tomcat

Remove $CATALINA_HOME/webapps/ROOT. Update $CATALINA_HOME/conf/server.xml, make sure that Host element look like the following text:

<Host name="localhost"  appBase="webapps"
      unpackWARs="true" autoDeploy="false" deployOnStartup="false">
  <Context path="" docBase="myApp"></Context>

It works with Tomcat 8. autoDeploy and deployOnStartup need to set to false to prevent tomcat from deploying myApp twice.

How do you set the startup page for debugging in an ASP.NET MVC application?

If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.

If you want to start at a different controller action see Mark's answer.

What's the difference between the atomic and nonatomic attributes?

This is explained in Apple's documentation, but below are some examples of what is actually happening.

Note that there is no "atomic" keyword, if you do not specify "nonatomic", then the property is atomic, but specifying "atomic" explicitly will result in an error.

If you do not specify "nonatomic", then the property is atomic, but you can still specify "atomic" explicitly in recent versions if you want to.

//@property(nonatomic, retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
    return userName;
}

- (void) setUserName:(UITextField *)userName_ {
    [userName_ retain];
    [userName release];
    userName = userName_;
}

Now, the atomic variant is a bit more complicated:

//@property(retain) UITextField *userName;
//Generates roughly

- (UITextField *) userName {
    UITextField *retval = nil;
    @synchronized(self) {
        retval = [[userName retain] autorelease];
    }
    return retval;
}

- (void) setUserName:(UITextField *)userName_ {
    @synchronized(self) {
      [userName_ retain];
      [userName release];
      userName = userName_;
    }
}

Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.

There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.

Space between Column's children in Flutter

There are many ways of doing it, I'm listing a few here.

  1. Use Container and give some height:

    Column(
      children: <Widget>[
        Widget1(),
        Container(height: 10), // set height
        Widget2(),
      ],
    )
    
  2. Use Spacer

    Column(
      children: <Widget>[
        Widget1(),
        Spacer(), // use Spacer
        Widget2(),
      ],
    )
    
  3. Use Expanded

    Column(
      children: <Widget>[
        Widget1(),
        Expanded(child: SizedBox()), // use Expanded
        Widget2(),
      ],
    )
    
  4. Use mainAxisAlignment

    Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    
  5. Use Wrap

    Wrap(
      direction: Axis.vertical, // make sure to set this
      spacing: 20, // set your spacing
      children: <Widget>[
        Widget1(),
        Widget2(),
      ],
    )
    

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

The condition has length > 1 and only the first element will be used

Like sgibb said it was an if problem, it had nothing to do with | or ||.

Here is another way to solve your problem:

for (i in 1:nrow(trip)) {
  if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "G:C to T:A"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "G:C to C:G"
  }
  else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
    trip[i, 'mutType'] <- "G:C to A:T"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
    trip[i, 'mutType'] <- "A:T to T:A"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
    trip[i, 'mutType'] <- "A:T to G:C"
  }
  else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
    trip[i, 'mutType'] <- "A:T to C:G"
  }
}

clear table jquery

I needed this:

$('#myTable tbody > tr').remove();

It deletes all rows except the header.

Twitter Bootstrap button click to toggle expand/collapse text section above button

It's possible to do this without using extra JS code using the data-collapse and data-target attributes on the a link.

e.g.

<a class="btn" data-toggle="collapse" data-target="#viewdetails">View details &raquo;</a>

Here's a working example.

Programmatically stop execution of python script?

The exit() and quit() built in functions do just what you want. No import of sys needed.

Alternatively, you can raise SystemExit, but you need to be careful not to catch it anywhere (which shouldn't happen as long as you specify the type of exception in all your try.. blocks).

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

Searching for file in directories recursively

You will want to move the loop for the files outside of the loop for the folders. In addition you will need to pass the data structure holding the collection of files to each call of the method. That way all files go into a single list.

public static List<string> DirSearch(string sDir, List<string> files)
{
  foreach (string f in Directory.GetFiles(sDir, "*.xml"))
  {
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
      files.Add(f);
    }
  }
  foreach (string d in Directory.GetDirectories(sDir))
  {
    DirSearch(d, files);
  }
  return files;
}

Then call it like this.

List<string> files = DirSearch("c:\foo", new List<string>());

Update:

Well unbeknownst to me, until I read the other answer anyway, there is already a builtin mechanism for doing this. I will leave my answer in case you are interested in seeing how your code needs to be modified to make it work.

List the queries running on SQL Server

There are various management views built into the product. On SQL 2000 you'd use sysprocesses. On SQL 2K5 there are more views like sys.dm_exec_connections, sys.dm_exec_sessions and sys.dm_exec_requests.

There are also procedures like sp_who that leverage these views. In 2K5 Management Studio you also get Activity Monitor.

And last but not least there are community contributed scripts like the Who Is Active by Adam Machanic.

How add spaces between Slick carousel item

Just fix css:

/* the slides */
.slick-slider {
    overflow: hidden;
}
/* the parent */
.slick-list {
    margin: 0 -9px;
}
/* item */  
.item{
    padding: 0 9px;
}

Docker official registry (Docker Hub) URL

For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be

docker.io/<dockerimagename>:version

The suggestion above of registry.hub.docker.com/library/<dockerimagename> did not work for me.

I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)

How do I vertical center text next to an image in html/css?

I recommend using tables with <td valign="middle"> (as inkedmn mentioned, it works in all browsers), but if you're wrapping with a link, here's how to do it (works in ugly old browsers too, like Opera 9):

<a href="/" style="display: block; vertical-align: middle;">
    <img src="/logo.png" style="vertical-align: middle;"/>
    <span style="vertical-align: middle;">Sample text</span>
</a>

How to generate entire DDL of an Oracle schema (scriptable)?

There is a problem with objects such as PACKAGE_BODY:

SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';


ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ??  "SYS.DBMS_METADATA", line 4018
ORA-06512: ??  "SYS.DBMS_METADATA", line 5843
ORA-06512: ??  line 1
31600. 00000 -  "invalid input value %s for parameter %s in function %s"
*Cause:    A NULL or invalid value was supplied for the parameter.
*Action:   Correct the input value and try the call again.



SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
  FROM all_OBJECTS 
  WHERE (OWNER = 'OWNER1');

displaying a string on the textview when clicking a button in android

You can do like this:

 String hello;
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    super.onCreate(savedInstanceState);

    mybtn = (Button)findViewById(R.id.mybtn);
    txtView=(TextView)findViewById(R.id.txtView);
    txtwidth = (TextView)findViewById(R.id.viewwidth);
    hello="This is my first project";


    mybtn.setOnClickListener(this);
}
public void onClick(View view){
    txtView.setText(hello);
}

Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file. Hope this will help you.

Matching strings with wildcard

Often, wild cards operate with two type of jokers:

  ? - any character  (one and only one)
  * - any characters (zero or more)

so you can easily convert these rules into appropriate regular expression:

  // If you want to implement both "*" and "?"
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; 
  }

  // If you want to implement "*" only
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; 
  }

And then you can use Regex as usual:

  String test = "Some Data X";

  Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
  Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
  Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));

  // Starts with S, ends with X, contains "me" and "a" (in that order) 
  Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));

How to disable auto-play for local video in iframe

<iframe width="420" height="315"
    src="https://www.youtube.com/embed/aNOgO7aNslo?rel=0">
</iframe>

You're supposed to put the characters ?rel=0 after the YouTube video unique link and before the quotations. it worked for me

Send email with PHPMailer - embed image in body

I found the answer:

$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');

and on the <img> tag put src='cid:logo_2u'

Android: ScrollView vs NestedScrollView

NestedScrollView as the name suggests is used when there is a need for a scrolling view inside another scrolling view. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll.

This is where NestedScrollView comes in.

python error: no module named pylab

I installed python-numpy python-scipy python-matplotlib, but it didn't work for me and I got the same error. Pylab isn't recognized without matplotlib. So I used this:

from matplotlib import pylab
from pylab import *

and worked for me.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

How to draw border on just one side of a linear layout?

As an alternative (if you don't want to use background), you can easily do it by making a view as follows:

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a right border only, place this after the layout (where you want to have the border):

<View
    android:layout_width="2dp"
    android:layout_height="match_parent"
    android:background="#000000" />

For having a left border only, place this before the layout (where you want to have the border):

Worked for me...Hope its of some help....

java.lang.OutOfMemoryError: Java heap space

  1. In most of the cases, the code is not optimized. Release those objects which you think shall not be needed further. Avoid creation of objects in your loop each time. Try to use caches. I don't know how your application is doing. But In programming, one rule of normal life applies as well

    Prevention is better than cure. "Don't create unnecessary objects"

Verify ImageMagick installation

You can easily check for the Imagick class in PHP.

if( class_exists("Imagick") )
{
    //Imagick is installed
}

How to solve PHP error 'Notice: Array to string conversion in...'

What the PHP Notice means and how to reproduce it:

If you send a PHP array into a function that expects a string like: echo or print, then the PHP interpreter will convert your array to the literal string Array, throw this Notice and keep going. For example:

php> print(array(1,2,3))

PHP Notice:  Array to string conversion in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array

In this case, the function print dumps the literal string: Array to stdout and then logs the Notice to stderr and keeps going.

Another example in a PHP script:

<?php
    $stuff = array(1,2,3);
    print $stuff;  //PHP Notice:  Array to string conversion in yourfile on line 3
?>

Correction 1: use foreach loop to access array elements

http://php.net/foreach

$stuff = array(1,2,3);
foreach ($stuff as $value) {
    echo $value, "\n";
}

Prints:

1
2
3

Or along with array keys

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
    echo "$key: $value\n";
}

Prints:

name: Joe
email: [email protected]

Note that array elements could be arrays as well. In this case either use foreach again or access this inner array elements using array syntax, e.g. $row['name']

Correction 2: Joining all the cells in the array together:

In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:

<?php
    $stuff = array(1,2,3);
    print implode(", ", $stuff);    //prints 1, 2, 3
    print join(',', $stuff);        //prints 1,2,3

Correction 3: Stringify an array with complex structure:

In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode

$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);

Prints

{"name":"Joe","email":"[email protected]"}

A quick peek into array structure: use the builtin php functions

If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose

examples

$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);

Prints:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Use the following script to find and kill all the opened connections to the database before restoring database.

declare @sql as varchar(20), @spid as int

select @spid = min(spid)  from master..sysprocesses  where dbid = db_id('<database_name>') 
and spid != @@spid    

while (@spid is not null)
begin
    print 'Killing process ' + cast(@spid as varchar) + ' ...'
    set @sql = 'kill ' + cast(@spid as varchar)
    exec (@sql)

    select 
        @spid = min(spid)  
    from 
        master..sysprocesses  
    where 
        dbid = db_id('<database_name>') 
        and spid != @@spid
end 

print 'Process completed...'

Hope this will help...

C++ convert string to hexadecimal and vice versa

Here is an other solution, largely inspired by the one by @fredoverflow.

/**
 * Return hexadecimal representation of the input binary sequence
 */
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
    std::ostringstream output;

    for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
        output << digits[beg >> 4] << digits[beg & 15];

    return output.str();
}

Length was required parameter in the intended usage.

how to check which version of nltk, scikit learn installed?

you may check from a python notebook cell as follows

!pip install --upgrade nltk     # needed if nltk is not already installed
import nltk      
print('The nltk version is {}.'.format(nltk.__version__))
print('The nltk version is '+ str(nltk.__version__))

and

#!pip install --upgrade sklearn      # needed if sklearn is not already installed
import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print('The scikit-learn version is '+ str(nltk.__version__))

Align image to left of text on same line - Twitter Bootstrap3

You can use floating:

<div class="paragraphs">
  <div class="row">
    <div class="span4">
      <img style="float:left" src="../site/img/success32.png"/>
      <div class="content-heading"><h3>Experience &nbsp </h3></div>
      <p style="clear:both">Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

If you want the following <p> to stay at the same line too, remove its

style="clear:both"

but then you should add

<div style="clear:both"></div>

after it.

Why does JavaScript only work after opening developer tools in IE once?

If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.

Simple service for logging. Default implementation safely writes the message into the browser's console (if present).

https://docs.angularjs.org/api/ng/service/$log

So if you have something similar to

angular.module('logExample', [])
  .controller('LogController', ['$scope', function($scope) {
    console.log('Hello World!');
 }]);

you can replace it with

angular.module('logExample', [])
  .controller('LogController', ['$scope', '$log', function($scope, $log) {
    $log.log('Hello World!');
 }]);

Angular 2+ does not have any built-in log service.

C# try catch continue execution

Why cant you use the finally block?

Like

try {

} catch (Exception e) {

  // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

} finally { 

 // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

}

EDIT after question amended:

You can do:

int? returnFromFunction2 = null;
    try {
        returnFromFunction2 = function2();
        return returnFromFunction2.value;
        } catch (Exception e) {

          // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

        } finally { 

        if (returnFromFunction2.HasValue) { // do something with value }

         // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

        }

Concatenating date with a string in Excel

Another approach

=CONCATENATE("Age as of ", TEXT(TODAY(),"dd-mmm-yyyy"))

This will return Age as of 06-Aug-2013

What does servletcontext.getRealPath("/") mean and when should I use it

My Method:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        String path = request.getRealPath("/WEB-INF/conf.properties");
        Properties p = new Properties();
        p.load(new FileInputStream(path));

        String StringConexion=p.getProperty("StringConexion");
        String User=p.getProperty("User");
        String Password=p.getProperty("Password");
    }
    catch(Exception e){
        String msg = "Excepcion " + e;
    }
}

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

You need to CAST the ParentId as an nvarchar, so that the output is always the same data type.

SELECT Id   'PatientId',
       ISNULL(CAST(ParentId as nvarchar(100)),'')  'ParentId'
FROM Patients

getResourceAsStream returns null

What worked for me was to add the file under My Project/Java Resources/src and then use

this.getClass().getClassLoader().getResourceAsStream("myfile.txt");

I didn't need to explicitly add this file to the path (adding it to /src does that apparently)

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

If App Pool has trouble restarting or simply doesn't want to restart, verify if windows made recent update on ASP.NET v4.0 or other App Pool. That is what happend in my case. I simply restarted my computer, then restarted ASP.NET v4.0 App Pool and everything was working again!

Click events on Pie Charts in Chart.js

Within options place your onclick and call the function you need as an example the ajax you need, I'll leave the example so that every click on a point tells you the value and you can use it in your new function.

    options: {
        plugins: {
            // Change options for ALL labels of THIS CHART
            datalabels: {
                color: 'white',
                //backgroundColor:'#ffce00',
                align: 'start'
            }
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    fontColor: "white"
                },gridLines: {
                        color: 'rgba(255,255,255,0.1)',
                        display: true
                    }
            }],
            xAxes: [{
                ticks: {
                    fontColor: "white"
                },gridLines: {                        
                        display: false
                    }
            }]
        },
        legend: {
        display: false

    },
    //onClick: abre     
        onClick:function(e){ 
    var activePoints = myChart.getElementsAtEvent(e); 
    var selectedIndex = activePoints[0]._index; 
    alert(this.data.datasets[0].data[selectedIndex]); 


} 
    }

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

How do I copy to the clipboard in JavaScript?

Here's an elegant solution for Angular 5.x+:

Component:

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnInit,
  Output,
  Renderer2,
  ViewChild
} from '@angular/core';

@Component({
  selector: 'copy-to-clipboard',
  templateUrl: './copy-to-clipboard.component.html',
  styleUrls: ['./copy-to-clipboard.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class CopyToClipboardComponent implements OnInit {
  @ViewChild('input') input: ElementRef;
  @Input() size = 'md';
  @Input() theme = 'complement';
  @Input() content: string;
  @Output() copied: EventEmitter<string> = new EventEmitter<string>();
  @Output() error: EventEmitter<string> = new EventEmitter<string>();

  constructor(private renderer: Renderer2) {}

  ngOnInit() {}

  copyToClipboard() {

    const rootElement = this.renderer.selectRootElement(this.input.nativeElement);

    // iOS Safari blocks programmtic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {

      this.renderer.setAttribute(this.input.nativeElement, 'contentEditable', 'true');

      const range = document.createRange();

      range.selectNodeContents(this.input.nativeElement);

      const sel = window.getSelection();

      sel.removeAllRanges();
      sel.addRange(range);

      rootElement.setSelectionRange(0, 999999);
    } else {
      rootElement.select();
    }

    try {
      document.execCommand('copy');
      this.copied.emit();
    } catch (err) {
      this.error.emit(err);
    }
  };
}

Template:

<button class="btn btn-{{size}} btn-{{theme}}" type="button" (click)="copyToClipboard()">
  <ng-content></ng-content>
</button>

<input #input class="hidden-input" [ngModel]="content">

Styles:

.hidden-input {
  position: fixed;
  top: 0;
  left: 0;
  width: 1px; 
  height: 1px;
  padding: 0;
  border: 0;
  box-shadow: none;
  outline: none;
  background: transparent;
}

What does "zend_mm_heap corrupted" mean

Had zend_mm_heap corrupted along with child pid ... exit signal Segmentation fault on a Debian server that was upgraded to jessie. After long investigation it turned out that XCache was installed prior Zend-Engine was generally available.

after apt-get remove php5-xcache and service apache2 restart the errors vanished.

How are ssl certificates verified?

It's worth noting that in addition to purchasing a certificate (as mentioned above), you can also create your own for free; this is referred to as a "self-signed certificate". The difference between a self-signed certificate and one that's purchased is simple: the purchased one has been signed by a Certificate Authority that your browser already knows about. In other words, your browser can easily validate the authenticity of a purchased certificate.

Unfortunately this has led to a common misconception that self-signed certificates are inherently less secure than those sold by commercial CA's like GoDaddy and Verisign, and that you have to live with browser warnings/exceptions if you use them; this is incorrect.

If you securely distribute a self-signed certificate (or CA cert, as bobince suggested) and install it in the browsers that will use your site, it's just as secure as one that's purchased and is not vulnerable to man-in-the-middle attacks and cert forgery. Obviously this means that it's only feasible if only a few people need secure access to your site (e.g., internal apps, personal blogs, etc.).

How can I make an EXE file from a Python program?

See a short list of python packaging tools on FreeHackers.org.

Is mongodb running?

I know this is for php, but I got here looking for a solution for node. Using mongoskin:

mongodb.admin().ping(function(err) {
    if(err === null)
        // true - you got a conntion, congratulations
    else if(err.message.indexOf('failed to connect') !== -1)
        // false - database isn't around
    else
        // actual error, do something about it
})

With other drivers, you can attempt to make a connection and if it fails, you know the mongo server's down. Mongoskin needs to actually make some call (like ping) because it connects lazily. For php, you can use the try-to-connect method. Make a script!

PHP:

$dbIsRunning = true
try {
  $m = new MongoClient('localhost:27017');
} catch($e) {
  $dbIsRunning = false
}

How to check that Request.QueryString has a specific value or not in ASP.NET?

You can also try:

if (!Request.QueryString.AllKeys.Contains("aspxerrorpath"))
   return;

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

Spring @ContextConfiguration how to put the right location for the xml

Simple solution is

@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml" })

from spring forum

MySQL select query with multiple conditions

@fthiella 's solution is very elegant.

If in future you want show more than user_id you could use joins, and there in one line could be all data you need.

If you want to use AND conditions, and the conditions are in multiple lines in your table, you can use JOINS example:

SELECT `w_name`.`user_id` 
     FROM `wp_usermeta` as `w_name`
     JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id` 
          AND `w_name`.`meta_key` = 'first_name' 
          AND `w_year`.`meta_key` = 'yearofpassing' 
     JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id 
          AND `w_city`.`meta_key` = 'u_city'
     JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id` 
          AND `w_course`.`meta_key` = 'us_course'
     WHERE 
         `w_name`.`meta_value` = '$us_name' AND         
         `w_year`.meta_value   = '$us_yearselect' AND 
         `w_city`.`meta_value` = '$us_reg' AND 
         `w_course`.`meta_value` = '$us_course'

Other thing: Recommend to use prepared statements, because mysql_* functions is not SQL injection save, and will be deprecated. If you want to change your code the less as possible, you can use mysqli_ functions: http://php.net/manual/en/book.mysqli.php

Recommendation:

Use indexes in this table. user_id highly recommend to be and index, and recommend to be the meta_key AND meta_value too, for faster run of query.

The explain:

If you use AND you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.

Tests: Table Data:

          PRIMARY                 INDEX
      int       varchar(255)    varchar(255)
       /                \           |
  +---------+---------------+-----------+
  | user_id | meta_key      | meta_value|
  +---------+---------------+-----------+
  | 1       | first_name    | Kovge     |
  +---------+---------------+-----------+
  | 1       | yearofpassing | 2012      |
  +---------+---------------+-----------+
  | 1       | u_city        | GaPa      |
  +---------+---------------+-----------+
  | 1       | us_course     | PHP       |
  +---------+---------------+-----------+

The result of Query with $us_name='Kovge' $us_yearselect='2012' $us_reg='GaPa', $us_course='PHP':

 +---------+
 | user_id |
 +---------+
 | 1       |
 +---------+

So it should works.

Is header('Content-Type:text/plain'); necessary at all?

It is very important that you tell the browser what type of data you are sending it. The difference should be obvious. Try viewing the output of the following PHP file in your browser;

<?php
header('Content-Type:text/html');
?>
<p>Hello</p>

You will see:

hello

(note that you will get the same results if you miss off the header line in this case - text/html is php's default)

Change it to text/plain

<?php
header('Content-Type:text/plain');
?>
<p>Hello</p>

You will see:

<p>Hello</p>

Why does this matter? If you have something like the following in a php script that, for example, is used by an ajax request:

<?php
header('Content-Type:text/html');
print "Your name is " . $_GET['name']

Someone can put a link to a URL like http://example.com/test.php?name=%3Cscript%20src=%22http://example.com/eviljs%22%3E%3C/script%3E on their site, and if a user clicks it, they have exposed all their information on your site to whoever put up the link. If you serve the file as text/plain, you are safe.

Note that this is a silly example, it's more likely that the bad script tag would be added by the attacker to a field in the database or by using a form submission.

Date query with ISODate in mongodb doesn't seem to work

In json strict mode, you'll have to keep the order:

{
    "dt": {
        "$gte": {
            "$date": "2013-10-01T00:00:00.000Z"
        }
    }
}

Only thing which worked to define my search queries on mlab.com.

Spring application context external properties?

This blog can help you. The trick is to use SpEL (spring expression language) to read the system properties like user.home, to read user home directory using SpEL you could use
#{ systemProperties['user.home']} expression inside your bean elements. For example to access your properties file stored in your home directory you could use the following in your PropertyPlaceholderConfigurer, it worked for me.

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>file:#{ systemProperties['user.home']}/ur_folder/settings.properties</value>
    </property>
</bean>

window.onload vs <body onload=""/>

Sorry for reincarnation of this thread again after another 3 years of sleeping, but perhaps I have finally found the indisputable benefit of window.onload=fn1; over <body onload="fn1()">. It concerns the JS modules or ES modules: when your onload handler resides in "classical" JS file (i.e. referred without <script type="module" … >, either way is possible; when your onload handler resides in "module" JS file (i.e. referred with <script type="module" … >, the <body onload="fn1()"> will fail with "fn1() is not defined" error. The reason perhaps is that the ES modules are not loaded before HTML is parsed … but it is just my guess. Anyhow, window.onload=fn1; works perfectly with modules ...

Converting JSON data to Java object

HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

How to hide iOS status bar

FIXED SOLUTION FOR SWIFT 3+ (iOS 9, 10)

1- In info.plist set below property

enter image description here

2- Paste below code to Root controller , To

 private var isStatusBarHidden = true {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    override var prefersStatusBarHidden: Bool {
        return isStatusBarHidden
    }

You can call isStatusBarHidden = true and isStatusBarHidden = false where you want to hide/show status bar

How to create multiple class objects with a loop in python?

I hope this is what you are looking for.

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

Output:

Hello

Object Dump JavaScript

In Chrome, click the 3 dots and click More tools and click developer. On the console, type console.dir(yourObject).Click this link to view an example image

How to open a specific port such as 9090 in Google Compute Engine

You'll need to add a firewall rule to open inbound access to tcp:9090 to your instances. If you have more than the two instances, and you only want to open 9090 to those two, you'll want to make sure that there is a tag that those two instances share. You can add or update tags via the console or the command-line; I'd recommend using the GUI for that if needed because it handles the read-modify-write cycle with setinstancetags.

If you want to open port 9090 to all instances, you can create a firewall rule like:

gcutil addfirewall allow-9090 --allowed=tcp:9090

which will apply to all of your instances.

If you only want to open port 9090 to the two instances that are serving your application, make sure that they have a tag like my-app, and then add a firewall like so:

gcutil addfirewall my-app-9090 --allowed=tcp:9090 --target_tags=my-app

You can read more about creating and managing firewalls in GCE here.

How to create EditText with cross(x) button at end of it?

Use the following layout:

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="9dp"
    android:padding="5dp">

    <EditText
        android:id="@+id/calc_txt_Prise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"  
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:textColor="@color/gray"
        android:textStyle="bold"
        android:hint="@string/calc_txt_Prise"
        android:singleLine="true" />

    <Button
        android:id="@+id/calc_clear_txt_Prise"      
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_gravity="right|center_vertical"
        android:background="@drawable/delete" />

</FrameLayout>

You can also use the button's id and perform whatever action you want on its onClickListener method.

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

I was asking the same too. Another solution is you could overload your method:

void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);

in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself

void remove_id(EmployeeClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(ProductClass _obj) {
    int saveId = _obj->id;
    ...
};

void remove_id(DepartmentClass _obj) {
    int saveId = _obj->id;
    ...
};

Android Studio Gradle Already disposed Module

For me this happened when I removed a module and tried to build the project:

Simple solution was to Invalidate the cache & Restart.

Android Studio>File>Invalidate Caches>Invalidate & Restart

LINQ's Distinct() on a particular property

Override Equals(object obj) and GetHashCode() methods:

class Person
{
    public int Id { get; set; }
    public int Name { get; set; }

    public override bool Equals(object obj)
    {
        return ((Person)obj).Id == Id;
        // or: 
        // var o = (Person)obj;
        // return o.Id == Id && o.Name == Name;
    }
    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

and then just call:

List<Person> distinctList = new[] { person1, person2, person3 }.Distinct().ToList();

Remove all HTMLtags in a string (with the jquery text() function)

Could you not just try it?

myContent = '<div id="test">Hello <span>world!</span></div>';
console.log($(myContent).text()); //Prints "Hello world!"

Note that you need to wrap the string in a jQuery object, otherwise it won't have a text method obviously.

Convert array of indices to 1-hot encoded numpy array

For 1-hot-encoding

   one_hot_encode=pandas.get_dummies(array)

For Example

ENJOY CODING

HintPath vs ReferencePath in Visual Studio

My own experience has been that it's best to stick to one of two kinds of assembly references:

  • A 'local' assembly in the current build directory
  • An assembly in the GAC

I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.

Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).

This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D

Hope that helps!

What is the size of ActionBar in pixels?

public int getActionBarHeight() {
    int actionBarHeight = 0;
    TypedValue tv = new TypedValue();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv,
                true))
            actionBarHeight = TypedValue.complexToDimensionPixelSize(
                    tv.data, getResources().getDisplayMetrics());
    } else {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                getResources().getDisplayMetrics());
    }
    return actionBarHeight;
}

Get first day of week in SQL Server

For those who need the answer at work and creating function is forbidden by your DBA, the following solution will work:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-1), YourDate) as DATE) as WeekStart
From.....

This gives the start of that week. Here I assume that Sundays are the start of weeks. If you think that Monday is the start, you should use:

select *,
cast(DATEADD(day, -1*(DATEPART(WEEKDAY, YouDate)-2), YourDate) as DATE) as WeekStart
From.....

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are using the same connection for the DataReader and the ExecuteNonQuery. This is not supported, according to MSDN:

Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.

Updated 2018: link to MSDN

How to access the contents of a vector from a pointer to the vector in C++?

Access it like any other pointer value:

std::vector<int>* v = new std::vector<int>();

v->push_back(0);
v->push_back(12);
v->push_back(1);

int twelve = v->at(1);
int one = (*v)[2];

// iterate it
for(std::vector<int>::const_iterator cit = v->begin(), e = v->end; 
    cit != e;  ++cit)
{
    int value = *cit;
}

// or, more perversely
for(int x = 0; x < v->size(); ++x)
{
    int value = (*v)[x];
}

// Or -- with C++ 11 support
for(auto i : *v)
{
   int value = i;
}

"Invalid signature file" when attempting to run a .jar

Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:314) at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:268) at java.util.jar.JarVerifier.processEntry(JarVerifier.java:316) at java.util.jar.JarVerifier.update(JarVerifier.java:228) at java.util.jar.JarFile.initializeVerifier(JarFile.java:383) at java.util.jar.JarFile.getInputStream(JarFile.java:450) at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:977) at sun.misc.Resource.cachedInputStream(Resource.java:77) at sun.misc.Resource.getByteBuffer(Resource.java:160) at java.net.URLClassLoader.defineClass(URLClassLoader.java:454) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

What helped me (IntelliJ IDEA 2016.3): File -> Project Structure -> Artifacts -> Add JAR -> Select Main Class -> Choose "copy to the output directory and link via manifest" -> OK -> Apply -> Build -> Build Artifacts... -> Build

how to insert value into DataGridView Cell?

This is perfect code but it cannot add a new row:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But this code can insert a new row:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

Fit website background image to screen size

Try this ,

 background: url(../IMAGES/background.jpg) no-repeat center center fixed; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

For more information , follow this Perfect Full Page Background Image !!

Is there a way to run Bash scripts on Windows?

In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.

HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.

I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:

I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.

However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).

I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).

Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.

The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.

I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.

The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.

I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.

There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.

How Best to Compare Two Collections in Java and Act on Them?

I think the easiest way to do that is by using apache collections api - CollectionUtils.subtract(list1,list2) as long the lists are of the same type.

Android AlertDialog Single Button

Alert Dialog

alert dialog with a single button.

alert dialog with an icon.

alert dialog with three-button.

alert dialog with a choice option, radio button.

alert dialog with the multi-choice option, checkbox button.

<resources>
    <string name="app_name">Alert Dialog</string>

    <string name="info_dialog">Info Dialog</string>
    <string name="icon_dialog">Icon Dialog</string>
    <string name="rate_dialog">Rate Dialog</string>
    <string name="singleOption_dialog">Single Options Dialog</string>
    <string name="multiOption_dialog">Multi Options Dialog</string>

    <string-array name="fruit_name">
        <item>Apple</item>
        <item>Banana</item>
        <item>Orange</item>
        <item>Grapes</item>
        <item>Watermelon</item>
        <item>Nothing</item>
    </string-array>
</resources>

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

    <Button
        android:id="@+id/info_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/info_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/icon_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/icon_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/rate_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/rate_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/single_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/singleOption_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />

    <Button
        android:id="@+id/multi_dialog"
        android:layout_width="300dp"
        android:layout_height="55dp"
        android:text="@string/multiOption_dialog"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="14sp" />
</LinearLayout>

public class MainActivity extends AppCompatActivity {

    String select;
    String[] fruitNames;
    Button infoDialog, iconDialog, rateDialog, singleOptionDialog, multiOptionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        infoDialog = findViewById(R.id.info_dialog);
        rateDialog = findViewById(R.id.rate_dialog);
        iconDialog = findViewById(R.id.icon_dialog);
        singleOptionDialog = findViewById(R.id.single_dialog);
        multiOptionDialog = findViewById(R.id.multi_dialog);
        infoDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoDialog();
            }
        });
        rateDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ratingDialog();
            }
        });
        iconDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconDialog();
            }
        });
        singleOptionDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SingleSelectionDialog();
            }
        });
        multiOptionDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultipleSelectionDialog();
            }
        });
    }

    /*Display information dialog*/
    private void infoDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Info");
        dialogBuilder.setMessage("Some informative message for the user to do that.");
        dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Display rating dialog*/
    private void ratingDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Rate Us");
        dialogBuilder.setMessage("If you liked it, please rate it. It will help us grow.");
        dialogBuilder.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.setNegativeButton("Leave it", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.setNeutralButton("May be, later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog with icons*/
    private void iconDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Info");
        dialogBuilder.setIcon(R.mipmap.ic_launcher_round);
        dialogBuilder.setMessage("You know, you could have provided some valuable message here!");
        dialogBuilder.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog to select single option*/
    private void SingleSelectionDialog() {
        fruitNames = getResources().getStringArray(R.array.fruit_name);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
        dialogBuilder.setTitle("Which fruit you want to eat?");
        dialogBuilder.setSingleChoiceItems(fruitNames, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //Toast.makeText(MainActivity.this, checkedItem, Toast.LENGTH_SHORT).show();
                select = fruitNames[i];
            }
        });
        dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Item selected: " + select, Toast.LENGTH_SHORT).show();
            }
        });
        dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
            }
        });
        dialogBuilder.create().show();
    }

    /*Dialog to select multiple options*/
    public void MultipleSelectionDialog() {
        final String[] items = {"Apple", "Banana", "Orange", "Grapes", "Watermelon"};
        final ArrayList<Integer> selectedList = new ArrayList<>();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choice multi item fruit list");
        builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked) {
                    selectedList.add(which);
                } else if (selectedList.contains(which)) {
                    selectedList.remove(which);
                }
            }
        });
        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ArrayList<String> selectedStrings = new ArrayList<>();
                for (int j = 0; j < selectedList.size(); j++) {
                    selectedStrings.add(items[selectedList.get(j)]);
                }
                Toast.makeText(getApplicationContext(), "Items selected: " + Arrays.toString(selectedStrings.toArray()), Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }
}

enter image description here

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

How to remove padding around buttons in Android?

I had the same problem and it seems that it is because of the background color of the button. Try changing the background color to another color eg:

android:background="@color/colorActive"

and see if it works. You can then define a style if you want for the button to use.

Python Pandas replicate rows in dataframe

This is an old question, but since it still comes up at the top of my results in Google, here's another way.

import pandas as pd
import numpy as np

df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))

Say you want to replicate the rows where col1="b".

reps = [3 if val=="b" else 1 for val in df.col1]
df.loc[np.repeat(df.index.values, reps)]

You could replace the 3 if val=="b" else 1 in the list interpretation with another function that could return 3 if val=="b" or 4 if val=="c" and so on, so it's pretty flexible.

how to set imageview src?

Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.

Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html

e.g.:

imageView.setImageResource(R.drawable.myimage);

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Not sure why all the fuss with web.config or a serializer class. The below code worked for me:

XmlSerializer xmlSerializer = new XmlSerializer(myEnvelope.GetType());

using (StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, myEnvelope);
    return textWriter.ToString();
}

Set custom attribute using JavaScript

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");

But you really should be using data followed with a dash and with its property, like:

<li ... data-icon="base.gif" ...>

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif";

How to escape strings in SQL Server using PHP?

I have been using this as an alternative of mysql_real_escape_string():

function htmlsan($htmlsanitize){
    return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
}
$data = "Whatever the value's is";
$data = stripslashes(htmlsan($data));

Java String.split() Regex

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String reg = "\\s*[a-zA-Z]+";

    String[] res = str.split(reg);
    for (String out : res) {
        if (!"".equals(out)) {
            System.out.print(out);
        }
    }

Output : + - * / < > >= <= ==

Node.js project naming conventions for files & folders

Node.js doesn't enforce any file naming conventions (except index.js). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.

close fancy box from function from within open 'fancybox'

For those who spent hours like me to find out the solution for inline type: window.setTimeout(function(){$.fancybox.close()},10);

How to get the size of a string in Python?

>>> s = 'abcd'
>>> len(s)
4

LIMIT 10..20 in SQL Server

as you found, this is the preferred sql server method:

SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
 ) a WHERE a.row > 5 and a.row <= 10

Offline Speech Recognition In Android (JellyBean)

Google did quietly enable offline recognition in that Search update, but there is (as yet) no API or additional parameters available within the SpeechRecognizer class. {See Edit at the bottom of this post} The functionality is available with no additional coding, however the user’s device will need to be configured correctly for it to begin working and this is where the problem lies and I would imagine why a lot of developers assume they are ‘missing something’.

Also, Google have restricted certain Jelly Bean devices from using the offline recognition due to hardware constraints. Which devices this applies to is not documented, in fact, nothing is documented, so configuring the capabilities for the user has proved to be a matter of trial and error (for them). It works for some straight away – For those that it doesn't, this is the ‘guide’ I supply them with.

  1. Make sure the default Android Voice Recogniser is set to Google not Samsung/Vlingo
  2. Uninstall any offline recognition files you already have installed from the Google Voice Search Settings
  3. Go to your Android Application Settings and see if you can uninstall the updates for the Google Search and Google Voice Search applications.
  4. If you can't do the above, go to the Play Store see if you have the option there.
  5. Reboot (if you achieved 2, 3 or 4)
  6. Update Google Search and Google Voice Search from the Play Store (if you achieved 3 or 4 or if an update is available anyway).
  7. Reboot (if you achieved 6)
  8. Install English UK offline language files
  9. Reboot
  10. Use utter! with a connection
  11. Switch to aeroplane mode and give it a try
  12. Once it is working, the offline recognition of other languages, such as English US should start working too.

EDIT: Temporarily changing the device locale to English UK also seems to kickstart this to work for some.

Some users reported they still had to reboot a number of times before it would begin working, but they all get there eventually, often inexplicably to what was the trigger, the key to which are inside the Google Search APK, so not in the public domain or part of AOSP.

From what I can establish, Google tests the availability of a connection prior to deciding whether to use offline or online recognition. If a connection is available initially but is lost prior to the response, Google will supply a connection error, it won’t fall-back to offline. As a side note, if a request for the network synthesised voice has been made, there is no error supplied it if fails – You get silence.

The Google Search update enabled no additional features in Google Now and in fact if you try to use it with no internet connection, it will error. I mention this as I wondered if the ability would be withdrawn as quietly as it appeared and therefore shouldn't be relied upon in production.

If you intend to start using the SpeechRecognizer class, be warned, there is a pretty major bug associated with it, which require your own implementation to handle.

Not being able to specifically request offline = true, makes controlling this feature impossible without manipulating the data connection. Rubbish. You’ll get hundreds of user emails asking you why you haven’t enabled something so simple!

EDIT: Since API level 23 a new parameter has been added EXTRA_PREFER_OFFLINE which the Google recognition service does appear to adhere to.

Hope the above helps.

Adding rows dynamically with jQuery

I have Tried something like this and its works fine;

enter image description here

this is the html part :

<table class="dd" width="100%" id="data">
<tr>
<td>Year</td>
<td>:</td>
<td><select name="year1" id="year1" >
<option value="2012">2012</option>
<option value="2011">2011</option>
</select></td>
<td>Month</td>
<td>:</td>
<td width="17%"><select name="month1" id="month1">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select></td>
<td width="7%">Week</td>
<td width="3%">:</td>
<td width="17%"><select name="week1" id="week1" >
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select></td>
<td width="8%">&nbsp;</td>
<td colspan="2">&nbsp;</td>
</tr>
<tr>
<td>Actual</td>
<td>:</td>
<td width="17%"><input name="actual1" id="actual1" type="text" /></td>
<td width="7%">Max</td>
<td width="3%">:</td>
<td><input name="max1" id="max1" type="text" /></td>
<td>Target</td>
<td>:</td>
<td><input name="target1" id="target1" type="text" /></td>
</tr>

this is Javascript part;

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(document).ready(function() {
var currentItem = 1;
$('#addnew').click(function(){
currentItem++;
$('#items').val(currentItem);
var strToAdd = '<tr><td>Year</td><td>:</td><td><select name="year'+currentItem+'" id="year'+currentItem+'" ><option value="2012">2012</option><option value="2011">2011</option></select></td><td>Month</td><td>:</td><td width="17%"><select name="month'+currentItem+'" id="month'+currentItem+'"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select></td><td width="7%">Week</td><td width="3%">:</td><td width="17%"><select name="week'+currentItem+'" id="week'+currentItem+'" ><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></td><td width="8%"></td><td colspan="2"></td></tr><tr><td>Actual</td><td>:</td><td width="17%"><input name="actual'+currentItem+'" id="actual'+currentItem+'" type="text" /></td><td width="7%">Max</td> <td width="3%">:</td><td><input name="max'+currentItem+'" id ="max'+currentItem+'"type="text" /></td><td>Target</td><td>:</td><td><input name="target'+currentItem+'" id="target'+currentItem+'" type="text" /></td></tr>';
  $('#data').append(strToAdd);

 });
 });

 //]]>
 </script>

Finaly PHP submit part:

    for( $i = 1; $i <= $count; $i++ )
{
    $year = $_POST['year'.$i];
    $month = $_POST['month'.$i];
    $week = $_POST['week'.$i];
    $actual = $_POST['actual'.$i];
    $max = $_POST['max'.$i];
    $target = $_POST['target'.$i];
    $extreme = $_POST['extreme'.$i];
    $que = "insert INTO table_name(id,year,month,week,actual,max,target) VALUES ('".$_POST['type']."','".$year."','".$month."','".$week."','".$actual."','".$max."','".$target."')";
    mysql_query($que);

}

you can find more details via Dynamic table row inserter

The most efficient way to implement an integer based power function pow(int, int)

Exponentiation by squaring.

int ipow(int base, int exp)
{
    int result = 1;
    for (;;)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }

    return result;
}

This is the standard method for doing modular exponentiation for huge numbers in asymmetric cryptography.

How to convert FormData (HTML5 object) to JSON

FormData method .entries and the for of expression is not supported in IE11 and Safari.

Here is a simplier version to support Safari, Chrome, Firefox and Edge

function formDataToJSON(formElement) {    
    var formData = new FormData(formElement),
        convertedJSON = {};

    formData.forEach(function(value, key) { 
        convertedJSON[key] = value;
    });

    return convertedJSON;
}

Warning: this answer doesn't work in IE11.
FormData doesn't have a forEach method in IE11.
I'm still searching for a final solution to support all major browsers.

Using PUT method in HTML form

I wrote an npm package called 'html-form-enhancer'. By dropping it into your HTML source, it takes over submission of forms with methods aside from GET and POST, and also adds application/json serialization.

<script type=module" src="html-form-enhancer.js"></script>

<form method="PUT">
...
</form>

How can I get the current screen orientation?

In case anyone would like to obtain meaningful orientation description (like that passed to onConfigurationChanged(..) with those reverseLandscape, sensorLandscape and so on), simply use getRequestedOrientation()

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Allow 2 decimal places in <input type="number">

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the HTML code

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.

toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

firefox proxy settings via command line

All the other answers here explain how to program your proxy settings into Firefox which is what WPAD was invented to do. If you have WPAD configured then just tell Firefox to use it to auto-detect its settings, as you would in the GUI.

Connection Settings

To do this from a cmd file or command line:

pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
popd

This of course requires you to have WPAD configured and working correctly. Also I believe prefs.js won't exist until you've run Firefox once.

How to create a stopwatch using JavaScript?

Two native solutions

  • performance.now --> Call to ... took 6.414999981643632 milliseconds.
  • console.time --> Call to ... took 5.815 milliseconds

The difference between both is precision.

For usage and explanation read on.



Performance.now (For microsecond precision use)

_x000D_
_x000D_
    var t0 = performance.now();
    doSomething();
    var t1 = performance.now();

    console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
            
    function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
    }
_x000D_
_x000D_
_x000D_

performance.now

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().



console.time

Example: (timeEnd wrapped in setTimeout for simulation)

_x000D_
_x000D_
console.time('Search page');
  doSomething();
console.timeEnd('Search page');
 

 function doSomething(){    
       for(i=0;i<1000000;i++){var x = i*i;}
 }
_x000D_
_x000D_
_x000D_

You can change the Timer-Name for different operations.

How to urlencode a querystring in Python?

Try this:

urllib.pathname2url(stringToURLEncode)

urlencode won't work because it only works on dictionaries. quote_plus didn't produce the correct output.

Completely removing phpMyAdmin

I had same problem. Try the following command. This solved my problem.

sudo apt-get install libapache2-mod-php5

Nesting await in Parallel.ForEach

I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;

 Parallel.ForEach(ids, i =>
{
    ICustomerRepo repo = new CustomerRepo();
    // Run this in thread which Parallel library occupied.
    var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
    customers.Add(cust);
});

Python: No acceptable C compiler found in $PATH when installing python

On Arch Linux run the following:

sudo pacman -S base-devel

Finding absolute value of a number without using Math.abs()

You can use :

abs_num = (num < 0) ? -num : num;

SQL - Update multiple records in one query

in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,

   UPDATE mst_users 
   SET base_id = CASE user_id 
   WHEN 78 THEN 999 
   WHEN 77 THEN 88 
   ELSE base_id END WHERE user_id IN(78, 77)

78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.

Test process.env with Jest

Expanding a bit on Serhan C.'s answer...

According to the blog post How to Setup dotenv with Jest Testing - In-depth Explanation, you can include "dotenv/config" directly in setupFiles, without having to create and reference an external script that calls require("dotenv").config().

I.e., simply do

module.exports = {
    setupFiles: ["dotenv/config"]
}

Proper way to exit iPhone application?

This has gotten a good answer but decided to expand a bit:

You can't get your application accepted to AppStore without reading Apple's iOS Human Interface Guidelines well. (they retain the right to reject you for doing anything against them) The section "Don't Quit Programmatically" http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html is an exact guideline in how you should treat in this case.

If you ever have a problem with Apple platform you can't easily find a solution for, consult HIG. It's possible Apple simply doesn't want you to do it and they usually (I'm not Apple so I can't guarantee always) do say so in their documentation.

How to identify a strong vs weak relationship on ERD?

In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.

Android: TextView: Remove spacing and padding on top and bottom

Add android:includeFontPadding="false" to see if it helps.And make text view size same as that of text size rather than "wrap content".It will definitely work.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

php REQUEST_URI

I think that parse_str is what you're looking for, something like this should do the trick for you:

parse_str($_SERVER['QUERY_STRING'], $vars);

Then the $vars array will hold all the passed arguments.

How to choose between Hudson and Jenkins?

As chmullig wrote, use Jenkins. Some additional points:

...and a little background info:

The creator of Hudson, Kohsuke Kawaguchi, started the project on his free time, even if he was working for Sun Microsystems and later paid by them to develop it further. As @erickson noted at another SO question,

[Hudson/Jenkins] is the product of a single genius intellect—Kohsuke Kawaguchi. Because of that, it's consistent, coherent, and rock solid.

After the acquisition by Oracle, Kohsuke didn't hang around for long (due to lack of monitors...? ;-]), and went to work for CloudBees. What started in late 2010 as conflict over tools between the dev community and Oracle and ended in the rename/fork/split is well documented in the links chmullig provided. To me, that whole conundrum speaks, perhaps more than anything else, to Oracle's utter inability or unwillingness to sponsor an open-source project in a way that keeps all parties (Oracle, developers, users) happy. It's not in their DNA or something, as we've seen in other cases too.

Given all of the above, I would personally follow Kohsuke and other core developers in this matter, and go with Jenkins.

How to create a timer using tkinter?

from tkinter import *

from tkinter import messagebox

root = Tk()

root.geometry("400x400")

root.resizable(0, 0)

root.title("Timer")

seconds = 21

def timer():

    global seconds
    if seconds > 0:
        seconds = seconds - 1
        mins = seconds // 60
        m = str(mins)

        if mins < 10:
            m = '0' + str(mins)
        se = seconds - (mins * 60)
        s = str(se)

        if se < 10:
            s = '0' + str(se)
        time.set(m + ':' + s)
        timer_display.config(textvariable=time)
        # call this function again in 1,000 milliseconds
        root.after(1000, timer)

    elif seconds == 0:
        messagebox.showinfo('Message', 'Time is completed')
        root.quit()


frames = Frame(root, width=500, height=500)

frames.pack()

time = StringVar()

timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'))

timer_display.place(x=145, y=100)

timer()  # start the timer

root.mainloop()

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

Angular - Can't make ng-repeat orderBy work

As mentioned, only arrays are allowed. But to make it simple for you, you could dynamically convert the object into an array via a piping function as seen here https://gist.github.com/brev/3949705

Just declare the filter, and add it to ng-repeat :)

<div ng-app="myApp">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-controller="Main">
  <div ng-repeat="release in releases | object2Array | orderBy:'environment_id'">{{release.environment_id}}</div>
</div>

<script>

var app = angular.module('myApp', []).filter('object2Array', function() {
    return function(input) {
      var out = []; 
      for(i in input){
        out.push(input[i]);
      }
      return out;
    }
  })
.controller('Main',function ($scope) {
        $scope.releases = {"tvl-c-wbap001 + tvl-webapp":{"timestamp":" 05:05:53 PM ","environment_id":"CERT5","release_header":"Projects/Dev","date":"19 Oct","release":"12.11.91-1"},"tvl-c-wbap401 + tvl-webapp":{"timestamp":" 10:07:25 AM ","environment_id":"CERT4","release_header":"Future Release","date":"15 Oct","release":"485-1"},"tvl-c-wbap301 + tvl-webapp":{"timestamp":" 07:59:48 AM ","environment_id":"CERT3","release_header":"Next Release","date":"15 Oct","release":"485-1"},"tvl-c-wbap201 + tvl-webapp":{"timestamp":" 03:34:07 AM ","environment_id":"CERT2","release_header":"Next Changes","date":"15 Oct","release":"13.12.3-1"},"tvl-c-wbap101 + tvl-webapp":{"timestamp":" 12:44:23 AM ","environment_id":"CERT1","release_header":"Production Mirror","date":"15 Oct","release":"13.11.309-1"},"tvl-s-wbap002 + tvl-webapp":{"timestamp":" 12:43:23 AM ","environment_id":"Stage2","date":"15 Oct","release":"13.11.310-1"},"tvl-s-wbap001 + tvl-webapp":{"timestamp":" 11:07:38 AM ","environment_id":"Stage1","release_header":"Production Mirror","date":"11 Oct","release":"13.11.310-1"},"tvl-p-wbap001 + tvl-webapp":{"timestamp":" 11:39:25 PM ","environment_id":"Production","release_header":"Pilots","date":"14 Oct","release":"13.11.310-1"},"tvl-p-wbap100 + tvl-webapp":{"timestamp":" 03:27:53 AM ","environment_id":"Production","release_header":"Non Pilots","date":"11 Oct","release":"13.11.309-1"}}
    });
</script>

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Exclusions and provided dependencies will not work in child projects.

If you are using inheritance in Maven projects you must include this configuration on the parent pom.xml file. You will have a <parent>...</parent> section in your pom.xml if you are using inheritance. So you will have something like this in your parent pom.xml:

<groupId>some.groupId</groupId>
<version>1.0</version>
<artifactId>someArtifactId</artifactId>
<packaging>pom</packaging>
<modules>
    <module>child-module-1</module>
    <module>child-module-2</module>
</modules>
<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

How to check if a file exists in the Documents directory in Swift?

Swift 4.2

extension URL    {
    func checkFileExist() -> Bool {
        let path = self.path
        if (FileManager.default.fileExists(atPath: path))   {
            print("FILE AVAILABLE")
            return true
        }else        {
            print("FILE NOT AVAILABLE")
            return false;
        }
    }
}

Using: -

if fileUrl.checkFileExist()
   {
      // Do Something
   }

How to skip the first n rows in sql query

Use this:

SELECT *
FROM Sales.SalesOrderHeader 
ORDER BY OrderDate
OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY

https://stackoverflow.com/a/19669165/1883345

Node.js Hostname/IP doesn't match certificate's altnames

I was getting this when streaming to ElasticSearch from a Lambda function in AWS. Smashed my head a against a wall trying to figure it out. In the end when setting the request.headers['Host'] I was adding in the https:// to the domain for ES - changing this to [es-domain-name].eu-west-1.es.amazonaws.com (without https://) worked straight away. Below is the code I used to get it working, hopefully save anyone else smashing their head against a wall...

import path from 'path';
import AWS from 'aws-sdk';

const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');

/**
 * Sends a request to Elasticsearch
 *
 * @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
 * @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
 * @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
 * @returns {Promise} Promise - object with the result of the HTTP response
 */
export function sendRequest ({ httpMethod, requestPath, payload }) {
    const request = new AWS.HttpRequest(endpoint, region);

    request.method = httpMethod;
    request.path = path.join(request.path, requestPath);
    request.body = payload;
    request.headers['Content-Type'] = 'application/json';
    request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
    request.headers['Content-Length'] = Buffer.byteLength(request.body);
    const signer = new AWS.Signers.V4(request, 'es');
    signer.addAuthorization(credentials, new Date());

    return new Promise((resolve, reject) => {
        httpClient.handleRequest(
            request,
            null,
            response => {
                const { statusCode, statusMessage, headers } = response;
                let body = '';
                response.on('data', chunk => {
                    body += chunk;
                });
                response.on('end', () => {
                    const data = {
                        statusCode,
                        statusMessage,
                        headers
                    };
                    if (body) {
                        data.body = JSON.parse(body);
                    }
                    resolve(data);
                });
            },
            err => {
                reject(err);
            }
        );
    });
}

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Get url parameters from a string in .NET

HttpContext.Current.Request.QueryString.Get("id");

Easy way to use variables of enum types as string in C?

There's no built-in solution. The easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.

Maven – Always download sources and javadocs

In my case the "settings.xml" solution didn't work so I use this command in order to download all the sources:

mvn dependency:sources

You also can use it with other maven commands, for example:

mvn clean install dependency:sources -Dmaven.test.skip=true

To download all documentation, use the following command:

mvn dependency:resolve -Dclassifier=javadoc

How do you convert an entire directory with ffmpeg?

For Linux and macOS this can be done in one line, using parameter expansion to change the filename extension of the output file:

for i in *.avi; do ffmpeg -i "$i" "${i%.*}.mp4"; done

Redefine tab as 4 spaces

I copied and pasted this into my .vimrc file:

" size of a hard tabstop
set tabstop=4

" always uses spaces instead of tab characters
set expandtab

" size of an "indent"
set shiftwidth=4

The first 2 settings mean that when I press Tab I get 4 spaces. The third setting means that when I do V> (i.e. visual and indent) I also get 4 spaces.

Not as comprehensive as the accepted answer but it might help people who just want something to copy and paste.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

Confirm deletion using Bootstrap 3 modal box

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

_x000D_
_x000D_
   _x000D_
_x000D_
 $('button[name="remove_levels"]').on('click', function(e) {_x000D_
      var $form = $(this).closest('form');_x000D_
      e.preventDefault();_x000D_
      $('#confirm').modal({_x000D_
          backdrop: 'static',_x000D_
          keyboard: false_x000D_
      })_x000D_
      .on('click', '#delete', function(e) {_x000D_
          $form.trigger('submit');_x000D_
        });_x000D_
      $("#cancel").on('click',function(e){_x000D_
       e.preventDefault();_x000D_
       $('#confirm').modal.model('hide');_x000D_
      });_x000D_
    });
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
  <div class="modal-body">_x000D_
    Are you sure?_x000D_
  </div>_x000D_
  <div class="modal-footer">_x000D_
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

Adjusting and image Size to fit a div (bootstrap)

Just a heads up that Bootstrap 4 now uses img-fluid instead of img-responsive, so double check which version you're using if you're having problems.

How do I escape a single quote in SQL Server?

I had the same problem, but mine was not based of static data in the SQL code itself, but from values in the data.

This code lists all the columns names and data types in my database:

SELECT DISTINCT QUOTENAME(COLUMN_NAME),DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS

But some column names actually have a single-quote embedded in the name of the column!, such as ...

[MyTable].[LEOS'DATACOLUMN]

To process these, I had to use the REPLACE function along with the suggested QUOTED_IDENTIFIER setting. Otherwise it would be a syntax error, when the column is used in a dynamic SQL.

SET QUOTED_IDENTIFIER OFF;
    SET @sql = 'SELECT DISTINCT ''' + @TableName + ''',''' + REPLACE(@ColumnName,"'","''") + ...etc
SET QUOTED_IDENTIFIER ON;

HttpGet with HTTPS : SSLPeerUnverifiedException

Note: Do not do this in production code, use http instead, or the actual self signed public key as suggested above.

On HttpClient 4.xx:

import static org.junit.Assert.assertEquals;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class HttpClientTrustingAllCertsTest {

    @Test
    public void shouldAcceptUnsafeCerts() throws Exception {
        DefaultHttpClient httpclient = httpClientTrustingAllSSLCerts();
        HttpGet httpGet = new HttpGet("https://host_with_self_signed_cert");
        HttpResponse response = httpclient.execute( httpGet );
        assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
    }

    private DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, getTrustingManager(), new java.security.SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        return httpclient;
    }

    private TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                // Do nothing
            }

        } };
        return trustAllCerts;
    }
}

Difference between File.separator and slash in paths

OK let's inspect some code.
File.java lines 428 to 435 in File.<init>:

String p = uri.getPath();
if (p.equals(""))
    throw new IllegalArgumentException("URI path component is empty");

// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);

And let's read fs/*(FileSystem)*/.fromURIPath() docs:

java.io.FileSystem
public abstract String fromURIPath(String path)
Post-process the given URI path string if necessary. This is used on win32, e.g., to transform "/c:/foo" into "c:/foo". The path string still has slash separators; code in the File class will translate them after this method returns.

This means FileSystem.fromURIPath() does post processing on URI path only in Windows, and because in the next line:

p = p.replace('/', File.separatorChar);

It replaces each '/' with system dependent seperatorChar, you can always be sure that '/' is safe in every OS.

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

Getting the parameters of a running JVM

If you can do this in java, try:

RuntimeMXBean

ManagementFactory

Example:

RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = runtimeMXBean.getInputArguments();
for (String arg : jvmArgs) {
    System.out.println(arg);
}

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They are both correct. Personally I prefer your approach better for its verbosity but it's really down to personal preference.

Off hand, running if($_POST) would not throw an error - the $_POST array exists regardless if the request was sent with POST headers. An empty array is cast to false in a boolean check.

json_encode is returning NULL?

You should pass utf8 encoded string in json_encode. You can use utf8_encode and array_map() function like below:

<?php
    $encoded_rows = array_map('utf8_encode', $rows);
    echo json_encode($encoded_rows);
?>

What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

Reading a text file using OpenFileDialog in windows forms

for this approach, you will need to add system.IO to your references by adding the next line of code below the other references near the top of the c# file(where the other using ****.** stand).

using System.IO;

this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))

both should be quite easy to understand and use.


    string pathToFile = "";//to save the location of the selected object
    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog theDialog = new OpenFileDialog();
        theDialog.Title = "Open Text File";
        theDialog.Filter = "TXT files|*.txt";
        theDialog.InitialDirectory = @"C:\";
        if (theDialog.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show(theDialog.FileName.ToString());
            pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object

        }

        if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
        {
            //method1
            string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
            string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();

            //method2
            string text = "";
            using(StreamReader sr =new StreamReader(pathToFile))
            {
                text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
            }
        }
    }

To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.


to add the data to your class you can use the constructor to add the data like:

  public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
        {
            EmployeeNum = EMPLOYEENUM;
            Name = NAME;
            Address = ADRESS;
            Wage = WAGE;
            Hours = HOURS;
        }

or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).

Resizing SVG in html?

Try these:

  1. Set the missing viewbox and fill in the height and width values of the set height and height attributes in the svg tag

  2. Then scale the picture simply by setting the height and width to the desired percent values. Good luck.

  3. Set a fixed aspect ratio with preserveAspectRatio="X200Y200 meet (e.g. 200px), but it's not necessary

e.g.

 <svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="10%" 
   height="10%"
   preserveAspectRatio="x200Y200 meet"
   viewBox="0 0 350 350"
   id="svg2"
   version="1.1"
   inkscape:version="0.48.0 r9654"
   sodipodi:docname="namesvg.svg">

How do you make strings "XML safe"?

Since PHP 5.4 you can use:

htmlspecialchars($string, ENT_XML1);

You should specify the encoding, such as:

htmlspecialchars($string, ENT_XML1, 'UTF-8');

Update

Note that the above will only convert:

  • & to &amp;
  • < to &lt;
  • > to &gt;

If you want to escape text for use in an attribute enclosed in double quotes:

htmlspecialchars($string, ENT_XML1 | ENT_COMPAT, 'UTF-8');

will convert " to &quot; in addition to &, < and >.


And if your attributes are enclosed in single quotes:

htmlspecialchars($string, ENT_XML1 | ENT_QUOTES, 'UTF-8');

will convert ' to &apos; in addition to &, <, > and ".

(Of course you can use this even outside of attributes).


See the manual entry for htmlspecialchars.

Can jQuery check whether input content has changed?

I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.

c# open a new form then close the current form?

I think this is much easier :)

    private void btnLogin_Click(object sender, EventArgs e)
    {
        //this.Hide();
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();
        //mm.Show();

        this.Hide();
        MainMenu mm = new MainMenu();
        mm.Show();

    }

Simplest way to set image as JPanel background

Simplest way to set image as JPanel background

Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual