Programs & Examples On #Hprof

A java heap/CPU profiling tool

Using msbuild to execute a File System Publish Profile

Actually I merged all your answers to my own solution how to solve the above problem:

  1. I create the pubxml file according my needs
  2. Then I copy all the parameters from pubxml file to my own list of parameters "/p:foo=bar" for msbuild.exe
  3. I throw away the pubxml file

The result is like that:

msbuild /t:restore /t:build /p:WebPublishMethod=FileSystem /p:publishUrl=C:\builds\MyProject\ /p:DeleteExistingFiles=True /p:LastUsedPlatform="Any CPU" /p:Configuration=Release

Could not find folder 'tools' inside SDK

For me it was a simple case of specifying the path to the 'sdk' subfolder rather than the top level folder.

In my case I needed to input

/Users/Myusername/Documents/adt-bundle-mac-x86_64-20140321/sdk

instead of

/Users/Myusername/Documents/adt-bundle-mac-x86_64-20140321

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

I can’t find the Android keytool

I never installed Java, but when you install Android Studio it has its own version within the Android directory. Here is where mine is located. Your path may be similar. After that you can either put the keytool into your path, or just run it from that directory.

C:\Program Files\Android\Android Studio\jre\bin

How do I analyze a .hprof file?

I personally prefer VisualVM. One of the features I like in VisualVM is heap dump comparison. When you are doing a heap dump analysis there are various ways to go about figuring out what caused the crash. One of the ways I have found useful is doing a comparison of healthy vs unhealthy heap dumps.

Following are the steps you can follow for it :

  1. Getting a heap dump of OutOfMemoryError let's call it "oome.hprof". You can get this via JVM parameter HeapDumpOnOutOfMemoryError.
  2. Restart the application let it run for a big (minutes/hours) depending on your application. Get another heap dump while the application is still running. Let's call it "healthy.hprof".
  3. You can open both these dumps in VisualVM and do a heap dump comparison. You can do it on class or package level. This can often point you into the direction of the issue.

link : https://visualvm.github.io

Eclipse Error: "Failed to connect to remote VM"

NOTE: For glassfish Server login via admin console -> Configurations -> server-config -> JVM-settings. * Remember to check Enable checkbox for Debug. Now Note the address, this address will be used in port of eclipse Remote Java Application Debug.Check the snap shot in glassfish server here

How to set back button text in Swift

Try this... it will work ....

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.title = ""
}

The above code will hide the text and show only the back arrow on navigation bar.

How to make correct date format when writing data to Excel

I know this question is old but populating Excell Cells with Dates via VSTO has a couple of gotchas.

I found Formula's don't work on dates with yyyy-mmm-dd format - even though the cells were DATE FORMAT! You have to translate Dates to a dd/mm/yyyy format for use in formula's.

For example the dates I am getting come back from SQL Analysis Server and I had to flip them and then format them:

using (var dateRn = xlApp.Range["A1"].WithComCleanup())
{
    dateRn.Resource.Value2 = Convert.ToDateTime(dateRn.Resource.Value2).ToString("dd-MMM-yyyy");
}


using (var rn = xlApp.Range["A1:A10"].WithComCleanup())
{
    rn.Resource.Select();
    rn.Resource.NumberFormat =  "d-mmm-yyyy;@";
}

Otherwise formula's using Dates doesn't work - the formula in cell C4 is the same as C3:

enter image description here

get all characters to right of last dash

string tail = test.Substring(test.LastIndexOf('-') + 1);

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

Get day of week in SQL Server 2005/2008

You can use DATEPART(dw, GETDATE()) but be aware that the result will rely on SQL server setting @@DATEFIRST value which is the first day of week setting (In Europe default value 7 which is Sunday).

If you want to change the first day of week to another value, you could use SET DATEFIRST but this may affect everywhere in your query session which you do not want.

Alternative way is to explicitly specify the first day of week value as parameter and avoid depending on @@DATEFIRST setting. You can use the following formula to achieve that when need it:

(DATEPART(dw, GETDATE()) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1

where @WeekStartDay is the first day of the week you want for your system (from 1 to 7 which means from Monday to Sunday).

I have wrapped it into below function so we can reuse it easily:

CREATE FUNCTION [dbo].[GetDayInWeek](@InputDateTime DATETIME, @WeekStartDay INT)
RETURNS INT
AS
BEGIN
    --Note: @WeekStartDay is number from [1 - 7] which is from Monday to Sunday
    RETURN (DATEPART(dw, @InputDateTime) + @@DATEFIRST + 6 - @WeekStartDay) % 7 + 1 
END

Example usage: GetDayInWeek('2019-02-04 00:00:00', 1)

It is equivalent to following (but independent to SQL server DATEFIRST setting):

SET DATEFIRST 1
DATEPART(dw, '2019-02-04 00:00:00')

Changing button color programmatically

use jquery :  $("#id").css("background","red");

How can I view the Git history in Visual Studio Code?

I recommend you this repository, https://github.com/DonJayamanne/gitHistoryVSCode

Git History Git History

It does exactly what you need and has these features:

  • View the details of a commit, such as author name, email, date, committer name, email, date and comments.
  • View a previous copy of the file or compare it against the local workspace version or a previous version.
  • View the changes to the active line in the editor (Git Blame).
  • Configure the information displayed in the list
  • Use keyboard shortcuts to view history of a file or line
  • View the Git log (along with details of a commit, such as author name, email, comments and file changes).

How to get Database Name from Connection String using SqlConnectionStringBuilder

string connectString = "Data Source=(local);" + "Integrated Security=true";

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);

Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);

How to use support FileProvider for sharing content to other apps?

If you get an image from camera none of these solutions work for Android 4.4. In this case it's better to check versions.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getContext().getPackageManager()) != null) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        uri = Uri.fromFile(file);
    } else {
        uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file);
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, CAMERA_REQUEST);
}

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I had the same problem but got it working by changing enable-oslogin from TRUE to FALSE in google cloud.

from:

to: enter image description here

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Bootstrap full-width text-input within inline-form

As stated in a similar question, try removing instances of the input-group class and see if that helps.

refering to bootstrap:

Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.

Check if object value exists within a Javascript array of objects and if not add a new object to array

I think that, this is the shortest way of addressing this problem. Here I have used ES6 arrow function with .filter to check the existence of newly adding username.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

function add(name) {
    var id = arr.length + 1;        
            if (arr.filter(item=> item.username == name).length == 0){
            arr.push({ id: id, username: name });
        }
}

add('ted');
console.log(arr);

Link to Fiddle

align right in a table cell with CSS

Use

text-align: right

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

See

text-align

<td class='alnright'>text to be aligned to right</td>

<style>
    .alnright { text-align: right; }
</style>

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

React-Router: No Not Found Route?

DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.

I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.

For react-router 1, 2 and 3

If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)

<Route path='*' exact={true} component={My404Component} />

If you want to display a 404 page but change the url (Same functionality as DefaultRoute)

<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />

Example with multiple levels:

<Route path='/' component={Layout} />
    <IndexRoute component={MyComponent} />
    <Route path='/users' component={MyComponent}>
        <Route path='user/:id' component={MyComponent} />
        <Route path='*' component={UsersNotFound} />
    </Route>
    <Route path='/settings' component={MyComponent} />
    <Route path='*' exact={true} component={GenericNotFound} />
</Route>

For react-router 4 and 5

Keep the path

<Switch>
    <Route exact path="/users" component={MyComponent} />
    <Route component={GenericNotFound} />
</Switch>

Redirect to another route (change url)

<Switch>
    <Route path="/users" component={MyComponent} />
    <Route path="/404" component={GenericNotFound} />
    <Redirect to="/404" />
</Switch>

The order matters!

Open mvc view in new window from controller

I assigned the javascript in my Controller:

model.linkCode = "window.open('https://www.yahoo.com', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))
        {
            WriteLiteral(Model.linkCode);
        }
    });

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.

How to get a float result by dividing two integer values using T-SQL?

Looks like this trick works in SQL Server and is shorter (based in previous answers)

SELECT 1.0*MyInt1/MyInt2

Or:

SELECT (1.0*MyInt1)/MyInt2

How do I find all files containing specific text on Linux?

grep is your good friend to achieve this.

grep -r <text_fo_find> <directory>

If you don't care about the case of the text to find, then use:

grep -ir <text_to_find> <directory>

Encoding conversion in java

CharsetDecoder should be what you are looking for, no ?

Many network protocols and files store their characters with a byte-oriented character set such as ISO-8859-1 (ISO-Latin-1).
However, Java's native character encoding is Unicode UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order).

See Charset. That doesn't mean UTF16 is the default charset (i.e.: the default "mapping between sequences of sixteen-bit Unicode code units and sequences of bytes"):

Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets.
[US-ASCII, ISO-8859-1 a.k.a. ISO-LATIN-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16]
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.

This example demonstrates how to convert ISO-8859-1 encoded bytes in a ByteBuffer to a string in a CharBuffer and visa versa.

// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
    // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
    // The new ByteBuffer is ready to be read.
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));

    // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    // The new ByteBuffer is ready to be read.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
} catch (CharacterCodingException e) {
}

What are unit tests, integration tests, smoke tests, and regression tests?

REGRESSION TESTING-

"A regression test re-runs previous tests against the changed software to ensure that the changes made in the current software do not affect the functionality of the existing software."

can't start MySql in Mac OS 10.6 Snow Leopard

  1. Change the following to the file /usr/local/mysql/support-files/mysql.server the follow lines:

    basedir="/usr/local/mysql"
    
    datadir="/usr/local/mysql/data"
    

    and save it.

  2. In the file /etc/rc.common add the follow line at end: /usr/local/mysql/bin/mysqld_safe --user=mysql &

Python: finding an element in a list

Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):

el = [x for x in mylist if x.attr == "foo"][0]

Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.

How to pass variable as a parameter in Execute SQL Task SSIS?

Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes

https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task

How to extract public key using OpenSSL?

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

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

Then

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

What is a stack pointer used for in microprocessors?

For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.

The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.

Read this one for more info.

General purpose use of a stack pointer register

How can I strip first and last double quotes?

If string is always as you show:

string[1:-1]

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

In my case I had a console application, I just unchecked Prefer 32-bit on Build projet properties tab and then I add this to my app.config:

<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Oracle.DataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="2.112.1.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

How can I copy a Python string?

You don't need to copy a Python string. They are immutable, and the copy module always returns the original in such cases, as do str(), the whole string slice, and concatenating with an empty string.

Moreover, your 'hello' string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.

One way you could work around this is to actually create a new string, then slice that string back to the original content:

>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)

But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.

If all you wanted to know is how much memory a Python object requires, use sys.getsizeof(); it gives you the memory footprint of any Python object.

For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:

>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360

You can then choose to use id() tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to

table.Variable2 LIKE '%' || :VarB || '%'

and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.

You could also change the Sql to

table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'

Unsupported operand type(s) for +: 'int' and 'str'

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

Get the data received in a Flask request

The raw data is passed in to the Flask application from the WSGI server as request.stream. The length of the stream is in the Content-Length header.

length = request.headers["Content-Length"]
data = request.stream.read(length)

It is usually safer to use request.get_data() instead.

How do I solve the "server DNS address could not be found" error on Windows 10?

There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.

  1. Go to Control Panel ? Network and Internet ? Network and Sharing Centre
  2. Click on Change Adapter settings.
  3. Right click on your connection icon (Wireless Network Connection or Local Area Connection) and select properties.
  4. Select Internet protocol version 4.
  5. Click on "Use the following DNS server address" and type either of the two DNS given below.

Google Public DNS

Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4

OpenDNS

Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220

How do I set a column value to NULL in SQL Server Management Studio?

If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl+0.

What is HEAD in Git?

I recommend this definition from github developer Scott Chacon [video reference]:

Head is your current branch. It is a symbolic reference. It is a reference to a branch. You always have HEAD, but HEAD will be pointing to one of these other pointers, to one of the branches that you're on. It is the parent of your next commit. It is what should be what was last checked-out into your working directory... This is the last known state of what your working directory was.

The whole video will give a fair introduction to the whole git system so I also recommend you to watch it all if have the time to.

Converting map to struct

Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

The second result parameter has to be an address of the struct.

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

Here is a function I made based on the answer above

def getDateToEpoch(myDateTime):
    res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
    return res

You can wrap the returned value like this : str(int(res)) To return it without a decimal value to be used as string or just int (without the str)

How to send email from SQL Server?

Step 1) Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.

Step 2)

RUN:

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

Step 3)

USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'

To loop through the table

DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)

SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]

WHILE @id<=@max_id
BEGIN
    SELECT @email_id=email_id 
    FROM [email_adresses]

    set @query='sp_send_dbmail @profile_name=''yourprofilename'',
                        @recipients='''+@email_id+''',
                        @subject=''Test message'',
                        @body=''This is the body of the test message.
                        Congrates Database Mail Received By you Successfully.'''

    EXEC @query
    SELECT @id=MIN(id) FROM [email_adresses] where id>@id

END

Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html

How can I force a hard reload in Chrome for Android

Don't forget to make sure that the "Reduce data usage" setting is turned OFF, as it seems to download cached data (from Google servers?) even though your local cache is flushed.

self.tableView.reloadData() not working in Swift

If your connection is in background thread then you should update UI in main thread like this

self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)

As I have mentioned here

Swift 4:

self.tblMainTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

How to set env variable in Jupyter notebook

A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE (no blank lines or extra spaces). You can source this file in the .bashrc or .bash_profile files when beginning a new terminal session and you can read this into a notebook with something like,

import os
env_vars = !cat ../script/.env
for var in env_vars:
    key, value = var.split('=')
    os.environ[key] = value

I used a relative path to show that this .env file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.

Git copy file preserving history

Unlike subversion, git does not have a per-file history. If you look at the commit data structure, it only points to the previous commits and the new tree object for this commit. No explicit information is stored in the commit object which files are changed by the commit; nor the nature of these changes.

The tools to inspect changes can detect renames based on heuristics. E.g. "git diff" has the option -M that turns on rename detection. So in case of a rename, "git diff" might show you that one file has been deleted and another one created, while "git diff -M" will actually detect the move and display the change accordingly (see "man git diff" for details).

So in git this is not a matter of how you commit your changes but how you look at the committed changes later.

Unique random string generation

Update 2016/1/23

If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:

Install-Package MlkPwgen

Then you can generate random strings just like in the answer below:

var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics);

One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.

Original Answer

Since no one has provided secure code yet, I post the following in case anyone finds it useful.

string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
    if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

    const int byteSize = 0x100;
    var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
    if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

    // Guid.NewGuid and System.Random are not particularly random. By using a
    // cryptographically-secure random number generator, the caller is always
    // protected, regardless of use.
    using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
        var result = new StringBuilder();
        var buf = new byte[128];
        while (result.Length < length) {
            rng.GetBytes(buf);
            for (var i = 0; i < buf.Length && result.Length < length; ++i) {
                // Divide the byte into allowedCharSet-sized groups. If the
                // random value falls into the last group and the last group is
                // too small to choose from the entire allowedCharSet, ignore
                // the value in order to avoid biasing the result.
                var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
                if (outOfRangeStart <= buf[i]) continue;
                result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
            }
        }
        return result.ToString();
    }
}

Thanks to Ahmad for pointing out how to get the code working on .NET Core.

Install a Windows service using a Windows command prompt?

Open Visual studio and select new project by selecting Windows Service template in Windows Desktop tab. Than copy following code into your service_name.cs file.

using System.Diagnostics;
using System.ServiceProcess;
namespace TimerService
{
    public partial class Timer_Service : ServiceBase
    {
        public Timer_Service()
        {
            InitializeComponent();
        }
        static void Main()
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Timer_Service service = new Timer_Service();
                service.OnStart(null);
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new Timer_Service()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
        protected override void OnStart(string[] args)
        {
            EventLog.WriteEvent("Timer_Service", new EventInstance(0, 0, EventLogEntryType.Information), new string[] { "Service start successfully." });
        }
        protected override void OnStop()
        {            
            EventLog.WriteEvent("Timer_Service", new EventInstance(0, 0, EventLogEntryType.Information), new string[] { "Service stop successfully." });
        }
    }
}

Right-Click on service_name.cs file and open designer of service. than right-click and select Add Installer. than right-click on serviceProcessInstaller1 and change its property value of Account from User to Local System.

Remove static void main method from Program.cs file. Than save and Build your project.

NOTE: goto bin\Ddebug folder of your project folder. Than open Properties of your service_name.exe file. Than goto Compatibility tab. Than click on Change Settings For All Users.

Select option Run this program as an administrator.

Now, You have to open CommandPromt as Administrator. After open, set directory to where your InstallUtil.exe file is placed. for ex: C:\Windows\Microsoft.NET\Framework64\v4.0.30319. now write the following command:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe -i C:\TimerService\TimerService\bin\Debug\TimerService.exe

Note: -i is for install he service and -u for Unsinstall.

after -i set the write the path where you want to install your service.

now write the command in CommandPromt as follows:

C:\TimerService\TimerService\bin\Debug>net start service_name

Note: use stop for stop the Service.

Now, open ViewEventLog.exe. Select Windows Logs>Application. There you can check your Service's log by start and stop the service.

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

Ajax request returns 200 OK, but an error event is fired instead of success

If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...

jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One to one (1-1) relationship: This is relationship between primary & foreign key (primary key relating to foreign key only one record). this is one to one relationship.

One to Many (1-M) relationship: This is also relationship between primary & foreign keys relationships but here primary key relating to multiple records (i.e. Table A have book info and Table B have multiple publishers of one book).

Many to Many (M-M): Many to many includes two dimensions, explained fully as below with sample.

-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CallTime DATETIME NOT NULL DEFAULT GETDATE(),
   CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
   ID INT IDENTITY(1, 1) NOT NULL,
   CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
   Subject VARCHAR(250) NOT NULL,
   Notes VARCHAR(8000) NOT NULL,
   Completed BIT NOT NULL DEFAULT 0
)
-- This table will link a phone call with a ticket.
CREATE TABLE dbo.PhoneCalls_Tickets
(
   PhoneCallID INT NOT NULL,
   TicketID INT NOT NULL
)

Get Absolute URL from Relative path (refactored method)

With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?

The Uri class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):

var uri = new Uri(absoluteUrl, relativeUrl);

If relativeUrl is in fact an abolute URL, then the absoluteUrl is ignored.

The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri constructor does not translate these).

Java heap terminology: young, old and permanent generations?

Memory in SunHotSpot JVM is organized into three generations: young generation, old generation and permanent generation.

  • Young Generation : the newly created objects are allocated to the young gen.
  • Old Generation : If the new object requests for a larger heap space, it gets allocated directly into the old gen. Also objects which have survived a few GC cycles gets promoted to the old gen i.e long lived objects house in old gen.
  • Permanent Generation : The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

FYI: The permanent gen is not considered a part of the Java heap.

How does the three generations interact/relate to each other? Objects(except the large ones) are first allocated to the young generation. If an object remain alive after x no. of garbage collection cycles it gets promoted to the old/tenured gen. Hence we can say that the young gen contains the short lived objects while the old gen contains the objects having a long life. The permanent gen does not interact with the other two generations.

Throw keyword in function's signature

Jalf already linked to it, but the GOTW puts it quite nicely why exception specifications are not as useful as one might hope:

int Gunc() throw();    // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)

Are the comments correct? Not quite. Gunc() may indeed throw something, and Hunc() may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.

That's just what it comes down to, you probably just will end up with a call to terminate() and your program dying a quick but painful death.

The GOTWs conclusion is:

So here’s what seems to be the best advice we as a community have learned as of today:

  • Moral #1: Never write an exception specification.
  • Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.

shorthand If Statements: C#

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();

Is it worth using Python's re.compile?

FWIW:

$ python -m timeit -s "import re" "re.match('hello', 'hello world')"
100000 loops, best of 3: 3.82 usec per loop

$ python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 1.26 usec per loop

so, if you're going to be using the same regex a lot, it may be worth it to do re.compile (especially for more complex regexes).

The standard arguments against premature optimization apply, but I don't think you really lose much clarity/straightforwardness by using re.compile if you suspect that your regexps may become a performance bottleneck.

Update:

Under Python 3.6 (I suspect the above timings were done using Python 2.x) and 2018 hardware (MacBook Pro), I now get the following timings:

% python -m timeit -s "import re" "re.match('hello', 'hello world')"
1000000 loops, best of 3: 0.661 usec per loop

% python -m timeit -s "import re; h=re.compile('hello')" "h.match('hello world')"
1000000 loops, best of 3: 0.285 usec per loop

% python -m timeit -s "import re" "h=re.compile('hello'); h.match('hello world')"
1000000 loops, best of 3: 0.65 usec per loop

% python --version
Python 3.6.5 :: Anaconda, Inc.

I also added a case (notice the quotation mark differences between the last two runs) that shows that re.match(x, ...) is literally [roughly] equivalent to re.compile(x).match(...), i.e. no behind-the-scenes caching of the compiled representation seems to happen.

update one table with data from another

For MySql:

UPDATE table1 JOIN table2 
    ON table1.id = table2.id
SET table1.name = table2.name,
    table1.`desc` = table2.`desc`

For Sql Server:

UPDATE   table1
SET table1.name = table2.name,
    table1.[desc] = table2.[desc]
FROM table1 JOIN table2 
   ON table1.id = table2.id

Activity transition in Android

You can do this with Activity.overridePendingTransition(). You can define simple transition animations in an XML resource file.

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

Converting a Uniform Distribution to a Normal Distribution

The Ziggurat algorithm is pretty efficient for this, although the Box-Muller transform is easier to implement from scratch (and not crazy slow).

Breaking out of a for loop in Java

You can use:

for (int x = 0; x < 10; x++) {
  if (x == 5) { // If x is 5, then break it.
    break;
  }
}

What is the meaning of @_ in Perl?

perldoc perlvar is the first place to check for any special-named Perl variable info.

Quoting:

@_: Within a subroutine the array @_ contains the parameters passed to that subroutine.

More details can be found in perldoc perlsub (Perl subroutines) linked from the perlvar:

Any arguments passed in show up in the array @_ .

Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_[1].

The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).

If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @_ removes that aliasing, and does not update any arguments.

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.

Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.

Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.

Write these down.

In a recent version of eclipse :

  • Go to Window -> Preferences -> General -> Network Connections=
  • Change the provider to "Manual"
  • Select the "HTTP" line and click the edit button
  • Add the IP address and port number above to the http line
  • If you have to authenticate to use the proxy,
    • select "Requires Authentication"
    • type in your username. Note that if your authentication is on a Windows domain, you might have to prepend the domain name and a backslash (\) like: MYDOMAIN\MYUSERID
    • Type in your password
  • Click OK
  • Click Apply
  • Click OK

At this point, you should be able to browse using the internal web browser (at least on http URLs).

Good luck.

Edit: Just so you know, it's WAY easier to use Nexus, one set of <mirror> tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

how to set the background image fit to browser using html

use background size: cover property . it will be full screen .

body{
background-size: cover;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
}

here is fiddle link

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

The following groovy script would be useful, if your job does not use "Source Code Management" directly (likewise "Git Parameter Plugin"), but still have access to a local (cloned) git repository:

import jenkins.model.Jenkins

def envVars = Jenkins.instance.getNodeProperties()[0].getEnvVars() 
def GIT_PROJECT_PATH = envVars.get('GIT_PROJECT_PATH') 
def gettags = "git ls-remote -t --heads origin".execute(null, new File(GIT_PROJECT_PATH))

return gettags.text.readLines()
         .collect { it.split()[1].replaceAll('\\^\\{\\}', '').replaceAll('refs/\\w+/', '')  }
         .unique()

See full explanation here: https://stackoverflow.com/a/37810768/658497

How do I import a .sql file in mysql database using PHP?

<?php
system('mysql --user=USER --password=PASSWORD DATABASE< FOLDER/.sql');
?>

How to create a file with a given size in Linux?

For small files:

dd if=/dev/zero of=upload_test bs=file_size count=1

Where file_size is the size of your test file in bytes.

For big files:

dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes

++i or i++ in for loops ??

As others have already noted, pre-increment is usually faster than post-increment for user-defined types. To understand why this is so, look at the typical code pattern to implement both operators:

Foo& operator++()
{
    some_member.increase();
    return *this;
}

Foo operator++(int dummy_parameter_indicating_postfix)
{
    Foo copy(*this);
    ++(*this);
    return copy;
}

As you can see, the prefix version simply modifies the object and returns it by reference.

The postfix version, on the other hand, must make a copy before the actual increment is performed, and then that copy is copied back to the caller by value. It is obvious from the source code that the postfix version must do more work, because it includes a call to the prefix version: ++(*this);

For built-in types, it does not make any difference as long as you discard the value, i.e. as long as you do not embed ++i or i++ in a larger expression such as a = ++i or b = i++.

How to size an Android view based on its parent's dimensions

I've been struggling this question for a long time, I want to change my DrawerLayout's drawer width, which is the second child of its parent. Recently I figured it out, but doesn't know if there's a better idea.

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    super.onLayout(changed, l, t, r, b)
    (getChildAt(1).layoutParams as LayoutParams).width = measuredWidth/2
}

Nginx: Permission denied for nginx on Ubuntu

This works for me,

sudo chmod -R 777 /var/log/nginx

How to replace spaces in file names using a bash script

I use:

for f in *\ *; do mv "$f" "${f// /_}"; done

Though it's not recursive, it's quite fast and simple. I'm sure someone here could update it to be recursive.

The ${f// /_} part utilizes bash's parameter expansion mechanism to replace a pattern within a parameter with supplied string. The relevant syntax is ${parameter/pattern/string}. See: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html or http://wiki.bash-hackers.org/syntax/pe .

Only numbers. Input number in React

Solution

Today I find use parseInt() is also a good and clean practice. A onChange(e) example is below.

Code

onChange(e){
    this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}

Explanation

  1. parseInt() would return NaN if the parameter is not a number.
  2. parseInt('12a') would return 12.

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

In order of activity, demos/examples available, and simplicity:

Related:

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

RichTextBox (WPF) does not have string property "Text"

The WPF RichTextBox has a Document property for setting the content a la MSDN:

// Create a FlowDocument to contain content for the RichTextBox.
        FlowDocument myFlowDoc = new FlowDocument();

        // Add paragraphs to the FlowDocument.
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
        myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
        RichTextBox myRichTextBox = new RichTextBox();

        // Add initial content to the RichTextBox.
        myRichTextBox.Document = myFlowDoc;

You can just use the AppendText method though if that's all you're after.

Hope that helps.

How to automatically reload a page after a given period of inactivity

And finally the most simple solution:

With alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout("IdleWarning()", timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Show idle timeout warning dialog.
    function IdleWarning() {
        var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){

                ResetTimers();
            }
            else{
                IdleTimeout();
            }
    }       

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Without alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout(timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Body code is the SAME for both solutions

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

Find an item in List by LINQ?

Here is one way to rewrite your method to use LINQ:

public static int GetItemIndex(string search)
{
    List<string> _list = new List<string>() { "one", "two", "three" };

    var result = _list.Select((Value, Index) => new { Value, Index })
            .SingleOrDefault(l => l.Value == search);

    return result == null ? -1 : result.Index;
}

Thus, calling it with

GetItemIndex("two") will return 1,

and

GetItemIndex("notthere") will return -1.

Reference: linqsamples.com

Change a Nullable column to NOT NULL with Default Value

I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are adding a column, but not if you are altering one.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created

UPDATE MyTable SET Created = GetDate() where Created IS NULL

ALTER TABLE dbo.MyTable 
ALTER COLUMN Created DATETIME NOT NULL 

How to get all Errors from ASP.Net MVC modelState?

In case anyone wants to return the Name of the Model property for binding the error message in a strongly typed view.

List<ErrorResult> Errors = new List<ErrorResult>();
foreach (KeyValuePair<string, ModelState> modelStateDD in ViewData.ModelState)
{
    string key = modelStateDD.Key;
    ModelState modelState = modelStateDD.Value;

    foreach (ModelError error in modelState.Errors)
    {
        ErrorResult er = new ErrorResult();
        er.ErrorMessage = error.ErrorMessage;
        er.Field = key;
        Errors.Add(er);
    }
}

This way you can actually tie the error in with the field that threw the error.

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

How to hide a status bar in iOS?

-(void) viewWillAppear:(BOOL)animated
{
     [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

How do I convert a org.w3c.dom.Document object to a String?

use some thing like

import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

//method to convert Document to String
public String getStringFromDocument(Document doc)
{
    try
    {
       DOMSource domSource = new DOMSource(doc);
       StringWriter writer = new StringWriter();
       StreamResult result = new StreamResult(writer);
       TransformerFactory tf = TransformerFactory.newInstance();
       Transformer transformer = tf.newTransformer();
       transformer.transform(domSource, result);
       return writer.toString();
    }
    catch(TransformerException ex)
    {
       ex.printStackTrace();
       return null;
    }
} 

Retrieve a Fragment from a ViewPager

Fragment yourFragment = yourviewpageradapter.getItem(int index);

index is the place of fragment in adapter like you added fragment1 first so retreive fragment1 pass index as 0 and so on for rest

When to use window.opener / window.parent / window.top

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

Creating a system overlay window (always on top)

WORKING ALWAYS ON TOP IMAGE BUTTON

first of all sorry for my english

i edit your codes and make working image button that listens his touch event do not give touch control to his background elements.

also it gives touch listeners to out of other elements

button alingments are bottom and left

you can chage alingments but you need to chages cordinats in touch event in the if element

import android.annotation.SuppressLint;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

public class HepUstte extends Service {
    HUDView mView;

    @Override
    public void onCreate() {
        super.onCreate();   

        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_LONG).show();

        final Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                R.drawable.logo_l);


        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                kangoo.getWidth(), 
                kangoo.getHeight(),
                WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                |WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                |WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                 PixelFormat.TRANSLUCENT);






        params.gravity = Gravity.LEFT | Gravity.BOTTOM;
        params.setTitle("Load Average");
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);



        mView = new HUDView(this,kangoo);

        mView.setOnTouchListener(new OnTouchListener() {


            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                //Log.e("kordinatlar", arg1.getX()+":"+arg1.getY()+":"+display.getHeight()+":"+kangoo.getHeight());
                if(arg1.getX()<kangoo.getWidth() & arg1.getY()>0)
                {
                 Log.d("tiklandi", "touch me");
                }
                return false;
            }
             });


        wm.addView(mView, params);



        }



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}



@SuppressLint("DrawAllocation")
class HUDView extends ViewGroup {


    Bitmap kangoo;

    public HUDView(Context context,Bitmap kangoo) {
        super(context);

        this.kangoo=kangoo;



    }


    protected void onDraw(Canvas canvas) {
        //super.onDraw(canvas);


        // delete below line if you want transparent back color, but to understand the sizes use back color
        canvas.drawColor(Color.BLACK);

        canvas.drawBitmap(kangoo,0 , 0, null); 


        //canvas.drawText("Hello World", 5, 15, mLoadPaint);

    }


    protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    }

    public boolean onTouchEvent(MotionEvent event) {
        //return super.onTouchEvent(event);
       // Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();

        return true;
    }
}

Can't perform a React state update on an unmounted component

I had a similar issue thanks @ford04 helped me out.

However, another error occurred.

NB. I am using ReactJS hooks

ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

What causes the error?

import {useHistory} from 'react-router-dom'

const History = useHistory()
if (true) {
  history.push('/new-route');
}
return (
  <>
    <render component />
  </>
)

This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.

What solution I found

import {Redirect} from 'react-router-dom'

if (true) {
  return <redirect to="/new-route" />
}
return (
  <>
    <render component />
  </>
)

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

var that = this; // this is a form
(new Thread(()=> {

    var action= new Action(() => {
       something
    }));

    if(!that.IsDisposed)
    {
        if(that.IsHandleCreated)
        {
            //if (that.InvokeRequired)
                that.BeginInvoke(action);
            //else
            // action.Invoke();
        }
        else
            that.HandleCreated+=(sender,event) => {
                action.Invoke();
            };
    }


})).Start();

How to convert DataTable to class Object?

Amit, I have used one way to achieve this with less coding and more efficient way.

but it uses Linq.

I posted it here because maybe the answer helps other SO.

Below DAL code converts datatable object to List of YourViewModel and it's easy to understand.

public static class DAL
{
        public static string connectionString = ConfigurationManager.ConnectionStrings["YourWebConfigConnection"].ConnectionString;

        // function that creates a list of an object from the given data table
        public static List<T> CreateListFromTable<T>(DataTable tbl) where T : new()
        {
            // define return list
            List<T> lst = new List<T>();

            // go through each row
            foreach (DataRow r in tbl.Rows)
            {
                // add to the list
                lst.Add(CreateItemFromRow<T>(r));
            }

            // return the list
            return lst;
        }

        // function that creates an object from the given data row
        public static T CreateItemFromRow<T>(DataRow row) where T : new()
        {
            // create a new object
            T item = new T();

            // set the item
            SetItemFromRow(item, row);

            // return 
            return item;
        }

        public static void SetItemFromRow<T>(T item, DataRow row) where T : new()
        {
            // go through each column
            foreach (DataColumn c in row.Table.Columns)
            {
                // find the property for the column
                PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

                // if exists, set the value
                if (p != null && row[c] != DBNull.Value)
                {
                    p.SetValue(item, row[c], null);
                }
            }
        }

        //call stored procedure to get data.
        public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
        {
            DataSet ds = new DataSet();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlConnection con = new SqlConnection(connectionString);

            try
            {
                cmd = new SqlCommand(SPName, con);
                cmd.Parameters.AddRange(SqlPrms);
                cmd.CommandTimeout = 240;
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(ds);
            }
            catch (Exception ex)
            {
               return ex;
            }

            return ds;
        }
}

Now, The way to pass and call method is below.

    DataSet ds = DAL.GetRecordWithExtendedTimeOut("ProcedureName");

    List<YourViewModel> model = new List<YourViewModel>();

    if (ds != null)
    {
        //Pass datatable from dataset to our DAL Method.
        model = DAL.CreateListFromTable<YourViewModel>(ds.Tables[0]);                
    }      

Till the date, for many of my applications, I found this as the best structure to get data.

How to read an http input stream

try this code

String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";

while ((line = br.readLine()) != null) {
    sb.append(line);
}

data = sb.toString();
System.out.println(data);

How to obfuscate Python code effectively?

so that it isn't human-readable?

i mean all the file is encoded !! when you open it you can't understand anything .. ! that what i want

As maximum, you can compile your sources into bytecode and then distribute only bytecode. But even this is reversible. Bytecode can be decompiled into semi-readable sources.

Base64 is trivial to decode for anyone, so it cannot serve as actual protection and will 'hide' sources only from complete PC illiterates. Moreover, if you plan to actually run that code by any means, you would have to include decoder right into the script (or another script in your distribution, which would needed to be run by legitimate user), and that would immediately give away your encoding/encryption.

Obfuscation techniques usually involve comments/docs stripping, name mangling, trash code insertion, and so on, so even if you decompile bytecode, you get not very readable sources. But they will be Python sources nevertheless and Python is not good at becoming unreadable mess.

If you absolutely need to protect some functionality, I'd suggest going with compiled languages, like C or C++, compiling and distributing .so/.dll, and then using Python bindings to protected code.

Rethrowing exceptions in Java without losing the stack trace

I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:

try
{
...
} catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {                    
    throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
}

Worked for me....:)

How to convert date to timestamp?

There are two problems here. First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.

Second, you need to pass it a string in a proper format.

Working example:

(new Date("2012-02-26")).getTime();

How to resize the jQuery DatePicker control

Not sure whether some body has suggested following way, if yes, just ignore my comments. I tested this today and it works for me. By just resizing the font before the control gets displayed:

$('#event_date').datepicker({
    showButtonPanel: true,
    dateFormat: "mm/dd/yy",
    beforeShow: function(){    
           $(".ui-datepicker").css('font-size', 12) 
    }
});

Using the callback function beforeShow

Is there an easy way to reload css without reloading the page?

Based on previous solutions, I have created bookmark with JavaScript code:

javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);

Image from Firefox:

enter image description here

What does it do?

It reloads CSS by adding query string params (as solutions above):

Coding Conventions - Naming Enums

In our codebase; we typically declare enums in the class that they belong to.

So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.

Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear, etc.

Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT). (side note; all our constants are in upper case)

As always, your coding standards probably differ from mine; so YMMV.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Hibernate dialect for Oracle Database 11g?

Use the Oracle 10g dialect. Also Hibernate 3.3.2+ is required for recent JDBC drivers (the internal class structure changed - symptoms will be whining about an abstract class).

Dialect of Oracle 11g is same as Oracle 10g (org.hibernate.dialect.Oracle10gDialect). Source: http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/session-configuration.html#configuration-optional-dialects

Easiest way to ignore blank lines when reading a file in Python

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

//App.js
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Google maps API V3 - multiple markers on exact same spot

@Ignatius most excellent answer, updated to work with v2.0.7 of MarkerClustererPlus.

  1. Add a prototype click method in the MarkerClusterer class, like so - we will override this later in the map initialize() function:

    // BEGIN MODIFICATION (around line 715)
    MarkerClusterer.prototype.onClick = function() { 
        return true; 
    };
    // END MODIFICATION
    
  2. In the ClusterIcon class, add the following code AFTER the click/clusterclick trigger:

    // EXISTING CODE (around line 143)
    google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
    google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
    
    // BEGIN MODIFICATION
    var zoom = mc.getMap().getZoom();
    // Trying to pull this dynamically made the more zoomed in clusters not render
    // when then kind of made this useless. -NNC @ BNB
    // var maxZoom = mc.getMaxZoom();
    var maxZoom = 15;
    // if we have reached the maxZoom and there is more than 1 marker in this cluster
    // use our onClick method to popup a list of options
    if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
        return mc.onClick(cClusterIcon);
    }
    // END MODIFICATION
    
  3. Then, in your initialize() function where you initialize the map and declare your MarkerClusterer object:

    markerCluster = new MarkerClusterer(map, markers);
    // onClick OVERRIDE
    markerCluster.onClick = function(clickedClusterIcon) { 
      return multiChoice(clickedClusterIcon.cluster_); 
    }
    

    Where multiChoice() is YOUR (yet to be written) function to popup an InfoWindow with a list of options to select from. Note that the markerClusterer object is passed to your function, because you will need this to determine how many markers there are in that cluster. For example:

    function multiChoice(clickedCluster) {
      if (clickedCluster.getMarkers().length > 1)
      {
        // var markers = clickedCluster.getMarkers();
        // do something creative!
        return false;
      }
      return true;
    };
    

How to get row count using ResultSet in Java?

Your function will return the size of a ResultSet, but its cursor will be set after last record, so without rewinding it by calling beforeFirst(), first() or previous() you won't be able to read its rows, and rewinding methods won't work with forward only ResultSet (you'll get the same exception you're getting in your second code fragment).

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

This can also be caused if you include bootstrap.js before jquery.js.

Others might have the same problem I did.

Include jQuery before bootstrap.

Phonegap Cordova installation Windows

I was having issues wtih installing phonegap. The issues were fixed when i run cmd as Administrator and then run command

npm install -g phonegap

and it is installed successfully.

Then in the directory where it is installed i opened cmd, and run command phonegap and it was working fine. Now going to play with it more :)

Thanks buddies for all this help.

Call a function after previous function is complete

Or you can trigger a custom event when one function completes, then bind it to the document:

function a() {
    // first function code here
    $(document).trigger('function_a_complete');
}

function b() {
    // second function code here
}

$(document).bind('function_a_complete', b);

Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.

PHP sessions that have already been started

Only if you want to destroy previous session :

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    }
    else
    {
        session_destroy();
        session_start(); 
    }
?>

or you can use

unset($_SESSION['variable_session _data'])

to destroy a particular session variable.

popup form using html/javascript/css

But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.

Umm. Just change the string passed to the prompt() function.

While searching, I found that there we CANNOT change the content of popup Prompt Box

You can't change the title. You can change the content, it is the first argument passed to the prompt() function.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Do you have a Python virtual environment that you need to enter before you run manage.py?

I ran into this error myself, and that was the problem.

TypeScript, Looping through a dictionary

Ians Answer is good, but you should use const instead of let for the key because it never gets updated.

for (const key in myDictionary) {
    let value = myDictionary[key];
    // Use `key` and `value`
}

No Application Encryption Key Has Been Specified

simply run

php artisan key:generate

its worked for me

Making macOS Installer Packages which are Developer ID ready

FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:

pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

jQuery Ajax File Upload

2019 update:

html

<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>

js

$(document).on('submit', '.fr', function(){

    $.ajax({ 
        type: 'post', 
        url: url, <--- you insert proper URL path to call your views.py function here.
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        data: new FormData(this) ,
        success: function(data) {
             console.log(data);
        }
        });
        return false;

    });

views.py

form = ThisForm(request.POST, request.FILES)

if form.is_valid():
    text = form.cleaned_data.get("text")
    example_image = request.FILES['example_image']

Single Page Application: advantages and disadvantages

I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:

If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

How do you round a floating point number in Perl?

You can either use a module like Math::Round:

use Math::Round;
my $rounded = round( $float );

Or you can do it the crude way:

my $rounded = sprintf "%.0f", $float;

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

adb not finding my device / phone (MacOS X)

I had a similar issue. I've discovered that MTP is not supported in OSX. I changed it to PTP, I was promoted to approve my laptop and then my device was finally listed (LG G3).

enter image description here

What are examples of TCP and UDP in real life?

Since tcp usages are pretty straightforward from other answers, I'll mention some interesting UDP use-cases:

1)DHCP - Dynamic Host Configuration Protocol, which is being used in order to dynamically assign IP address and some other network configuration to the connecting devices. In simple words, this protocol allows you just connect to the network cable(or wifi) and start using the internet, without any additional configurations. DHCP uses UDP protocol. Since the settings request message is being broadcasted from the host and there is no way to establish a TCP connection with DHCP server(you don't know it's address) it's impossible to use TCP instead.

2)Traceroute - well-known network diagnostic tool which allows you to explore which path in the network your datagram passes to reach it's destination(and how much time it takes). By default, it works by sending UDP datagram with unlikely destination port number(ranging from 33434 to 33534) to the destination with the ttl(time-to-live) field set to 1. When the router somewhere in the network gets such datagram - it finds out that the datagram is expired. Then, the router drops the datagram and sends to the origin of the datagram an ICMP(Internet Control Message Protocol) error message indicating that the datagram's ttl was expired and containing router's name and IP address. Each time the host sends datagrams with higher and higher TTL, thus increasing the network part which it succeeds to overcome and getting new ICMP messages from new routers. When it eventually reaches it's destination(datagrams TTL is big enough to allow it),- the destination host sends 'Destination port unreachable' ICMP message to the origin host. This way, Traceroute knows that the destination was reached. Since the TCP guarantees segments delivery it would be at least inefficient to use it instead of UDP which, in turn, allows datagram to be just dropped without any resend attempts(resend is implemented on the higher level, with continuously increasing TTL as described above).

How do I launch the Android emulator from the command line?

open CMD

  1. Open Command Prompt
  2. type the path of emulator in my case

C:\adt-bundle-windows-x86_64-20140702\sdk\tools enter image description here

  1. write "emulator -avd emulatorname" in my case

emulator -avd AdilVD

enter image description here

SVN commit command

Step1. $ cd [your working path of code]

Step2. $ svn commit [your server path ] -m 'Add commit message'

For help use $ svn help commit

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

sort json object in javascript

First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

One option might be to make your data look like this:

var json = [{
    "name": "user1",
    "id": 3
}, {
    "name": "user2",
    "id": 6
}, {
    "name": "user3",
    "id": 1
}];

Now you have an array of objects, and we can sort it.

json.sort(function(a, b){
    return a.id - b.id;
});

The resulting array will look like:

[{
    "name": "user3",
    "id" : 1
}, {
    "name": "user1",
    "id" : 3
}, {
    "name": "user2",
    "id" : 6
}];

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Android EditText Max Length

I had the same problem. It works perfectly fine when you add this:

android:inputType="textFilter"

to your EditText.

Insert current date into a date column using T-SQL?

If you're looking to store the information in a table, you need to use an INSERT or an UPDATE statement. It sounds like you need an UPDATE statement:

UPDATE  SomeTable
SET     SomeDateField = GETDATE()
WHERE   SomeID = @SomeID

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

How to git reset --hard a subdirectory?

Try changing

git checkout -- a

to

git checkout -- `git ls-files -m -- a`

Since version 1.7.0, Git's ls-files honors the skip-worktree flag.

Running your test script (with some minor tweaks changing git commit... to git commit -q and git status to git status --short) outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba

Running your test script with the proposed checkout change outputs:

Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
 D a/a/aa
 D a/b/ab
 M b/a/ba
After checkout:
 M b/a/ba
a/a/aa
a/b/ab
b/a/ba

What is the size of column of int(11) in mysql in bytes?

Though this answer is unlikely to be seen, I think the following clarification is worth making:

  • the (n) behind an integer data type in MySQL is specifying the display width
  • the display width does NOT limit the length of the number returned from a query
  • the display width DOES limit the number of zeroes filled for a zero filled column so the total number matches the display width (so long as the actual number does not exceed the display width, in which case the number is shown as is)
  • the display width is also meant as a useful tool for developers to know what length the value should be padded to

A BIT OF DETAIL
the display width is, apparently, intended to provide some metadata about how many zeros to display in a zero filled number.
It does NOT actually limit the length of a number returned from a query if that number goes above the display width specified.
To know what length/width is actually allowed for an integer data type in MySQL see the list & link: (types: TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT);
So having said the above, you can expect the display width to have no affect on the results from a standard query, unless the columns are specified as ZEROFILL columns
OR
in the case the data is being pulled into an application & that application is collecting the display width to use for some other sort of padding.

Primary Reference: https://blogs.oracle.com/jsmyth/entry/what_does_the_11_mean

Get folder name of the file in Python

You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.

Like this:

import os
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name  :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )

The output of the above was this:

Full Path    :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name  :app_02
Folder Parent:dev

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

No need to increase the MaxConnections & InitialConnections. Just close your connections after after doing your work. For example if you are creating connection:

try {
     connection = DriverManager.getConnection(
                    "jdbc:postgresql://127.0.0.1/"+dbname,user,pass);

   } catch (SQLException e) {
    e.printStackTrace();
    return;
}

After doing your work close connection:

try {
    connection.commit();
    connection.close();
} catch (SQLException e) {
    e.printStackTrace();
}

How to remove the querystring and get only the url?

If you want to get request path (more info):

echo parse_url($_SERVER["REQUEST_URI"])['path']

If you want to remove the query and (and maybe fragment also):

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);

How to read the RGB value of a given pixel in Python?

Image manipulation is a complex topic, and it's best if you do use a library. I can recommend gdmodule which provides easy access to many different image formats from within Python.

Getting hold of the outer class object from the inner class object

Have been edited in 2020-06-15

public class Outer {

    public Inner getInner(){
        return new Inner(this);
    }

    static class Inner {

        public final Outer Outer;

        public Inner(Outer outer) {
            this.Outer=outer;
        }
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        Inner inner = outer.getInner();
        Outer anotherOuter=inner.Outer;

        if(anotherOuter == outer) {
            System.out.println("Was able to reach out to the outer object via inner !!");
        } else {
            System.out.println("No luck :-( ");
        }
    }
}

Writing data into CSV file in C#

UPDATE

Back in my naïve days, I suggested doing this manually (it was a simple solution to a simple question), however due to this becoming more and more popular, I'd recommend using the library CsvHelper that does all the safety checks, etc.

CSV is way more complicated than what the question/answer suggests.

Original Answer

As you already have a loop, consider doing it like this:

//before your loop
    var csv = new StringBuilder();

//in your loop
    var first = reader[0].ToString();
    var second = image.ToString();
    //Suggestion made by KyleMit
    var newLine = string.Format("{0},{1}", first, second);
    csv.AppendLine(newLine);  

//after your loop
    File.WriteAllText(filePath, csv.ToString());

Or something to this effect. My reasoning is: you won't be need to write to the file for every item, you will only be opening the stream once and then writing to it.

You can replace

File.WriteAllText(filePath, csv.ToString());

with

File.AppendAllText(filePath, csv.ToString());

if you want to keep previous versions of csv in the same file

C# 6

If you are using c# 6.0 then you can do the following

var newLine = $"{first},{second}"

EDIT

Here is a link to a question that explains what Environment.NewLine does.

Update built-in vim on Mac OS X

A note to romainl's answer: aliases don't work together with sudo because only the first word is checked on aliases. To change this add another alias to your .profile / .bashrc:

alias sudo='sudo '

With this change sudo vim will behave as expected!

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

How to trim white space from all elements in array?

String val = "hi hello prince";
String arr[] = val.split(" ");

for (int i = 0; i < arr.length; i++)
{   
     System.out.print(arr[i]);
}

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

What is the fastest factorial function in JavaScript?

Here is one using newer javascript functions fill, map, reduce and constructor (and fat arrow syntax):

Math.factorial = n => n === 0 ? 1 : Array(n).fill(null).map((e,i)=>i+1).reduce((p,c)=>p*c)

Edit: updated to handle n === 0

Resetting a form in Angular 2 after submit

When I was going through the Angular basics guide on forms, and hit the resetting of forms section, I was very much left in surprise when I read the following in regards to the solution they give.

This is a temporary workaround while we await a proper form reset feature.

I personally haven't tested if the workaround they provided works (i assume it does), but I believe it is not neat, and that there must be a better way to go about the issue.

According to the FormGroup API (which is marked as stable) there already is a 'reset' method.

I tried the following. In my template.html file i had

<form (ngSubmit)="register(); registrationForm.reset();" #registrationForm="ngForm">
    ...
</form>

Notice that in the form element, I've initialised a template reference variable 'registrationForm' and initialized it to the ngForm Directive, which "governs the form as a whole". This gave me access to the methods and attributes of the governing FormGroup, including the reset() method.

Binding this method call to the ngSubmit event as show above reset the form (including pristine, dirty, model states etc) after the register() method is completed. For a demo this is ok, however it isn't very helpful for real world applications.

Imagine the register() method performs a call to the server. We want to reset the form when we know that the server responded back that everything is OK. Updating the code to the following caters for this scenario.

In my template.html file :

<form (ngSubmit)="register(registrationForm);" #registrationForm="ngForm">
    ...
</form>

And in my component.ts file :

@Component({
  ...
})
export class RegistrationComponent {
  register(form: FormGroup) {

   ...

   // Somewhere within the asynchronous call resolve function
   form.reset();
  }
}

Passing the 'registrationForm' reference to the method would allow us to call the reset method at the point of execution that we want to.

Hope this helps you in any way. :)

Note: This approach is based on Angular 2.0.0-rc.5

remove script tag from HTML content

This is a simplified variant of Dejan Marjanovic's answer:

function removeTags($html, $tag) {
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    foreach (iterator_to_array($dom->getElementsByTagName($tag)) as $item) {
        $item->parentNode->removeChild($item);
    }
    return $dom->saveHTML();
}

Can be used to remove any kind of tag, including <script>:

$scriptlessHtml = removeTags($html, 'script');

How to find all occurrences of an element in a list

more_itertools.locate finds indices for all items that satisfy a condition.

from more_itertools import locate


list(locate([0, 1, 1, 0, 1, 0, 0]))
# [1, 2, 4]

list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))
# [1, 3]

more_itertools is a third-party library > pip install more_itertools.

How to get text box value in JavaScript

 var jobValue=document.FormName.txtJob.value;

Try that code above.

jobValue : variable name.
FormName : Name of the form in html.
txtJob : Textbox name

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

When the Nexus 7 is plugged in there is a persistent notification that indicates "CONNECT AS / Media Device (MTP)". In this state adb devices will not show the Nexus, or undoubtedly any other device. Not exactly obvious, but if you select the second option "Camera (PTP)" the device is available for debugging (the lesson is ignore the camera, and focus on the protocol PTP).

This configuration is persistent, and I'm guessing that with a brand new device it will connect as MTP until told otherwise.

Thanks to @Ciaran Gallagher Settings --> Storage --> Top Left Option (Computer USB Connection) tap--> choose MTP

Why am I getting InputMismatchException?

Instead of using a dot, like: 1.2, try to input like this: 1,2.

C++ variable has initializer but incomplete type?

You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat into scope before you can create the local variable in main. I recommend that you move the definition of the type Cat to a header and include it from the translation unit that has main.

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

PostgreSQL - SQL state: 42601 syntax error

Your function would work like this:

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS 
$$
BEGIN

RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;

END     
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
  • You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.

  • The aggregate function count() returns bigint, but you had rowcount defined as integer, so you need an explicit cast ::int to make this work

  • I use dollar quoting to avoid quoting hell.

However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.

Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)

The query itself seems rather odd, btw. But that's beside the point here.

Getting the class of the element that fired an event using JQuery

If you are using jQuery 1.7:

alert($(this).prop("class"));

or:

alert($(event.target).prop("class"));

RE error: illegal byte sequence on Mac OS X

mklement0's answer is great, but I have some small tweaks.

It seems like a good idea to explicitly specify bash's encoding when using iconv. Also, we should prepend a byte-order mark (even though the unicode standard doesn't recommend it) because there can be legitimate confusions between UTF-8 and ASCII without a byte-order mark. Unfortunately, iconv doesn't prepend a byte-order mark when you explicitly specify an endianness (UTF-16BE or UTF-16LE), so we need to use UTF-16, which uses platform-specific endianness, and then use file --mime-encoding to discover the true endianness iconv used.

(I uppercase all my encodings because when you list all of iconv's supported encodings with iconv -l they are all uppercase.)

# Find out MY_FILE's encoding
# We'll convert back to this at the end
FILE_ENCODING="$( file --brief --mime-encoding MY_FILE )"
# Find out bash's encoding, with which we should encode
# MY_FILE so sed doesn't fail with 
# sed: RE error: illegal byte sequence
BASH_ENCODING="$( locale charmap | tr [:lower:] [:upper:] )"
# Convert to UTF-16 (unknown endianness) so iconv ensures
# we have a byte-order mark
iconv -f "$FILE_ENCODING" -t UTF-16 MY_FILE > MY_FILE.utf16_encoding
# Whether we're using UTF-16BE or UTF-16LE
UTF16_ENCODING="$( file --brief --mime-encoding MY_FILE.utf16_encoding )"
# Now we can use MY_FILE.bash_encoding with sed
iconv -f "$UTF16_ENCODING" -t "$BASH_ENCODING" MY_FILE.utf16_encoding > MY_FILE.bash_encoding
# sed!
sed 's/.*/&/' MY_FILE.bash_encoding > MY_FILE_SEDDED.bash_encoding
# now convert MY_FILE_SEDDED.bash_encoding back to its original encoding
iconv -f "$BASH_ENCODING" -t "$FILE_ENCODING" MY_FILE_SEDDED.bash_encoding > MY_FILE_SEDDED
# Now MY_FILE_SEDDED has been processed by sed, and is in the same encoding as MY_FILE

Convert SVG to image (JPEG, PNG, etc.) in the browser

I recently discovered a couple of image tracing libraries for JavaScript that indeed are able to build an acceptable approximation to the bitmap, both size and quality. I'm developing this JavaScript library and CLI :

https://www.npmjs.com/package/svg-png-converter

Which provides unified API for all of them, supporting browser and node, non depending on DOM, and a Command line tool.

For converting logos/cartoon/like images it does excellent job. For photos / realism some tweaking is needed since the output size can grow a lot.

It has a playground although right now I'm working on a better one, easier to use, since more features has been added:

https://cancerberosgx.github.io/demos/svg-png-converter/playground/#

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use the directions API.

Make an ajax call i.e.

https://maps.googleapis.com/maps/api/directions/json?parameters

and then parse the responce

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

scale Image in an UIButton to AspectFit?

The cleanest solution is to use Auto Layout. I lowered Content Compression Resistance Priority of my UIButton and set the image (not Background Image) via Interface Builder. After that I added a couple of constraints that define size of my button (quite complex in my case) and it worked like a charm.

JavaScript: set dropdown selected item based on option text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

How to display a loading screen while site content loads

#Pure css method

Place this at the top of your code (before header tag)

_x000D_
_x000D_
<style> .loader {_x000D_
  position: fixed;_x000D_
  background-color: #FFF;_x000D_
  opacity: 1;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 10;_x000D_
}_x000D_
</style>
_x000D_
<div class="loader">_x000D_
  Your Content For Load Screen_x000D_
</div>
_x000D_
_x000D_
_x000D_

And This At The Bottom after all other code (except /html tag)

_x000D_
_x000D_
<style>_x000D_
.loader {_x000D_
    -webkit-animation: load-out 1s;_x000D_
    animation: load-out 1s;_x000D_
    -webkit-animation-fill-mode: forwards;_x000D_
    animation-fill-mode: forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    }_x000D_
_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_
    }_x000D_
}_x000D_
_x000D_
@keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    }_x000D_
_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_
    }_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

This always works for me 100% of the time

Datatables - Search Box outside datatable

You can use the sDom option for this.

Default with search input in its own div:

sDom: '<"search-box"r>lftip'

If you use jQuery UI (bjQueryUI set to true):

sDom: '<"search-box"r><"H"lf>t<"F"ip>'

The above will put the search/filtering input element into it's own div with a class named search-box that is outside of the actual table.

Even though it uses its special shorthand syntax it can actually take any HTML you throw at it.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

Merging three dicts a,b,c in a single line without any other modules or libs

If we have the three dicts

a = {"a":9}
b = {"b":7}
c = {'b': 2, 'd': 90}

Merge all with a single line and return a dict object using

c = dict(a.items() + b.items() + c.items())

Returning

{'a': 9, 'b': 2, 'd': 90}

How can I call controller/view helper methods from the console in Ruby on Rails?

For controllers, you can instantiate a controller object in the Ruby on Rails console.

For example,

class CustomPagesController < ApplicationController

  def index
    @customs = CustomPage.all
  end

  def get_number
    puts "Got the Number"
  end

  protected

  def get_private_number
    puts 'Got private Number'
  end

end

custom = CustomPagesController.new
2.1.5 :011 > custom = CustomPagesController.new
 => #<CustomPagesController:0xb594f77c @_action_has_layout=true, @_routes=nil, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil>
2.1.5 :014 > custom.get_number
Got the Number
 => nil

# For calling private or protected methods,
2.1.5 :048 > custom.send(:get_private_number)
Got private Number
 => nil

Why does the Google Play store say my Android app is incompatible with my own device?

If you're here in 2020 and you think the device receiving the error message should be compatible:

Several other major apps have run into this including Instagram (1B+ installs) and Clash of Clans (100M+ installs). It appears to be an issue with Google's Android operating system.

To fix the “your device is not compatible with this version” error message, try clearing the Google Play Store cache, and then data. Next, restart the Google Play Store and try installing the app again.

[https://support.getupside.com/hc/en-us/articles/226667067--Device-not-compatible-error-message-in-Google-Play-Store]

Here is a link to Google's official support page that you can link to your users on how to clear the cache: https://support.google.com/googleplay/answer/7513003

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

I think the answer from cheez (https://stackoverflow.com/users/122933/cheez) is the easiest and most effective one. I'd elaborate a little bit over it so it would not modify a numpy function for the whole session period.

My suggestion is below. I´m using it to download the reuters dataset from keras which is showing the same kind of error:

old = np.load
np.load = lambda *a,**k: old(*a,**k,allow_pickle=True)

from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)

np.load = old
del(old)

How to handle anchor hash linking in AngularJS

I could do this like so:

<li>
<a href="#/#about">About</a>
</li>

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Import Google Play Services library in Android Studio

I had similar issue Cannot resolve com.google.android.gms.common.

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

  1. Installed/Updated Google Play Services, and Google Repository from SDK Manager
  2. Added dependency in build.gradle: compile 'com.google.android.gms:play-services:4.0.30'
  3. Updated AndroidManifest.xml with <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

ImageView rounded corners

I use Universal Image loader library to download and round the corners of image, and it worked for me.

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(thisContext)
            // You can pass your own memory cache implementation
           .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
           .build();

DisplayImageOptions options = new DisplayImageOptions.Builder()
            .displayer(new RoundedBitmapDisplayer(10)) //rounded corner bitmap
            .cacheInMemory(true)
            .cacheOnDisc(true)
            .build();

ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
imageLoader.displayImage(image_url,image_view, options );

How to tell git to use the correct identity (name and email) for a given project?

You need to use the local set command below:

local set

git config user.email [email protected]
git config user.name 'Mahmoud Zalt'

local get

git config --get user.email
git config --get user.name

The local config file is in the project directory: .git/config.

global set

git config --global user.email [email protected]
git config --global user.name 'Mahmoud Zalt'

global get

git config --global --get user.email
git config --global --get user.name

The global config file in in your home directory: ~/.gitconfig.

Remember to quote blanks, etc, for example: 'FirstName LastName'

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

Group list by values

len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
  newlist[key].append(item)

You can do it in a single list comprehension, perhaps more elegant but O(n**2):

[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]

Migration: Cannot add foreign key constraint

In laravel 5.8, the users_table uses bigIncrements('id') data type for the primary key. So that when you want to refer a foreign key constraint your user_id column needs to be unsignedBigInteger('user_id') type.

What’s the best RESTful method to return total number of items in an object?

As of "X-"-Prefix was deprecated. (see: https://tools.ietf.org/html/rfc6648)

We found the "Accept-Ranges" as being the best bet to map the pagination ranging: https://tools.ietf.org/html/rfc7233#section-2.3 As the "Range Units" may either be "bytes" or "token". Both do not represent a custom data type. (see: https://tools.ietf.org/html/rfc7233#section-4.2) Still, it is stated that

HTTP/1.1 implementations MAY ignore ranges specified using other units.

Which indicates: using custom Range Units is not against the protocol, but it MAY be ignored.

This way, we would have to set the Accept-Ranges to "members" or whatever ranged unit type, we'd expect. And in addition, also set the Content-Range to the current range. (see: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.12)

Either way, I would stick to the recommendation of RFC7233 (https://tools.ietf.org/html/rfc7233#page-8) to send a 206 instead of 200:

If all of the preconditions are true, the server supports the Range
header field for the target resource, and the specified range(s) are
valid and satisfiable (as defined in Section 2.1), the server SHOULD
send a 206 (Partial Content) response with a payload containing one
or more partial representations that correspond to the satisfiable
ranges requested, as defined in Section 4.

So, as a result, we would have the following HTTP header fields:

For Partial Content:

206 Partial Content
Accept-Ranges: members
Content-Range: members 0-20/100

For full Content:

200 OK
Accept-Ranges: members
Content-Range: members 0-20/20

"pip install json" fails on Ubuntu

While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

sudo apt install libpython2.7-stdlib

And then you can do import json in python and it would work!

Fully custom validation error message with Rails

Related to the accepted answer and another answer down the list:

I'm confirming that nanamkim's fork of custom-err-msg works with Rails 5, and with the locale setup.

You just need to start the locale message with a caret and it shouldn't display the attribute name in the message.

A model defined as:

class Item < ApplicationRecord
  validates :name, presence: true
end

with the following en.yml:

en:
  activerecord:
    errors:
      models:
        item:
          attributes:
            name:
              blank: "^You can't create an item without a name."

item.errors.full_messages will display:

You can't create an item without a name

instead of the usual Name You can't create an item without a name

What is the use of GO in SQL Server Management Studio & Transact SQL?

Go means, whatever SQL statements are written before it and after any earlier GO, will go to SQL server for processing.

Select * from employees;
GO    -- GO 1

update employees set empID=21 where empCode=123;
GO    -- GO 2

In the above example, statements before GO 1 will go to sql sever in a batch and then any other statements before GO 2 will go to sql server in another batch. So as we see it has separated batches.

How to add jQuery code into HTML Page

  1. Create a file for the jquery eg uploadfuntion.js.
  2. Save that file in the same folder as website or in subfolder.
  3. In head section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

and then the reference to your script eg: <script src="uploadfuntion.js"> </script>

4.Lastly you should ensure there are elements that match the selectors in the code.

Can we pass an array as parameter in any function in PHP?

even more cool, you can pass a variable count of parameters to a function like this:

function sendmail(...$users){
   foreach($users as $user){

   }
}

sendmail('user1','user2','user3');

How do I obtain a list of all schemas in a Sql Server database

For 2005 and later, these will both give what you're looking for.

SELECT name FROM sys.schemas
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA

For 2000, this will give a list of the databases in the instance.

SELECT * FROM INFORMATION_SCHEMA.SCHEMATA

That's the "backward incompatability" noted in @Adrift's answer.

In SQL Server 2000 (and lower), there aren't really "schemas" as such, although you can use roles as namespaces in a similar way. In that case, this may be the closest equivalent.

SELECT * FROM sysusers WHERE gid <> 0

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Scrolling to element using webdriver?

There is another option to scroll page to required element if element has "id" attribute

If you want to navigate to page and scroll down to element with @id, it can be done automatically by adding #element_id to URL...

Example

Let's say we need to navigate to Selenium Waits documentation and scroll page down to "Implicit Wait" section. We can do

driver.get('https://selenium-python.readthedocs.io/waits.html')

and add code for scrolling...OR use

driver.get('https://selenium-python.readthedocs.io/waits.html#implicit-waits')

to navigate to page AND scroll page automatically to element with id="implicit-waits" (<div class="section" id="implicit-waits">...</div>)

jQuery UI Datepicker - Multiple Date Selections

http://t1m0n.name/air-datepicker/docs/? I've have tried several method of multi datepicker but only this works

Using Google maps API v3 how do I get LatLng with a given address?

If you need to do this on the backend you can use the following URL structure:

https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]

Sample PHP code using curl:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

$json = curl_exec($curl);

curl_close ($curl);

$obj = json_decode($json);

See additional documentation for more details and expected json response.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.

Linking dll in Visual Studio

I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).

This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.

Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.

Example

Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h") then compile and link with B.lib:

cl A.cpp /c /EHsc
link A.obj B.lib

The first line generates A.obj, the second generates A.exe. The /c flag tells cl not to link and /EHsc specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).

If you don't specify /c cl will call link for you. You can use the /link flag to specify additional arguments to link and do it all at once if you like:

cl A.cpp /EHsc /link B.lib

If B.lib is not on the INCLUDE path you can give a relative or absolute path to it or add its parent directory to your include path with the /I flag.

If you're calling from cygwin (as I do) replace the forward slashes with dashes.

If you write #pragma comment(lib, "B.lib") in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.

How to open local file on Jupyter?

simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.

How to clear gradle cache?

As @Bradford20000 pointed out in the comments, there might be a gradle.properties file as well as global gradle scripts located under $HOME/.gradle. In such case special attention must be paid when deleting the content of this directory.

The .gradle/caches directory holds the Gradle build cache. So if you have any error about build cache, you can delete it.

The --no-build-cache option will run gradle without the build cache.

How to use random in BATCH script?

@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)ELSE set C=1&set D=2&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
title %random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %D%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&IF %D% EQU 9 (set D=1)ELSE set /A D=%D%+1)ELSE set /A C=%C%+1)&goto Y

simplified with multiple IF statements and plenty of ((()))

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

Just putting .encode('utf-8') at the end of object will do the job in recent versions of Python.

How to read a local text file?

_x000D_
_x000D_
var input = document.getElementById("myFile");_x000D_
var output = document.getElementById("output");_x000D_
_x000D_
_x000D_
input.addEventListener("change", function () {_x000D_
  if (this.files && this.files[0]) {_x000D_
    var myFile = this.files[0];_x000D_
    var reader = new FileReader();_x000D_
    _x000D_
    reader.addEventListener('load', function (e) {_x000D_
      output.textContent = e.target.result;_x000D_
    });_x000D_
    _x000D_
    reader.readAsBinaryString(myFile);_x000D_
  }   _x000D_
});
_x000D_
<input type="file" id="myFile">_x000D_
<hr>_x000D_
<textarea style="width:500px;height: 400px" id="output"></textarea>
_x000D_
_x000D_
_x000D_

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I just had the same message with the following code (in IcedCoffeeScript):

f = (err,cb) ->
  cb null, true

await f defer err, res
console.log err if err  

This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:

f (err,res) ->
  console.log err if err

What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.

The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:

f = (cb) ->
  cb null, true
f (err,res) ->
  console.log err if err

In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.

In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.

Why does DEBUG=False setting make my django Static Files Access fail?

Support for string view arguments to url() is deprecated and will be removed in Django 1.10

My solution is just small correction to Conrado solution above.

from django.conf import settings
import os
from django.views.static import serve as staticserve

if settings.DEBUG404:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', staticserve,
            {'document_root': os.path.join(os.path.dirname(__file__), 'static')} ),
        )

Remove a string from the beginning of a string

This will remove first match wherever it is found i.e., start or middle or end.

$str = substr($str, 0, strpos($str, $prefix)).substr($str, strpos($str, $prefix)+strlen($prefix));

Apply CSS style attribute dynamically in Angular JS

ngStyle directive allows you to set CSS style on an HTML element dynamically.

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

ng-style="{color: myColor}"

Your code will be:

<div ng-style="{'width':'20px', 'height':'20px', 'margin-top':'10px', 'border':'solid 1px black', 'background-color':'#ff0000'}"></div>

If you want to use scope variables:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Here an example on fiddle that use ngStyle, and below the code with the running snippet:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
.controller('MyCtrl', function($scope) {_x000D_
  $scope.items = [{_x000D_
      name: 'Misko',_x000D_
      title: 'Angular creator'_x000D_
    }, {_x000D_
      name: 'Igor',_x000D_
      title: 'Meetup master'_x000D_
    }, {_x000D_
      name: 'Vojta',_x000D_
      title: 'All-around superhero'_x000D_
    }_x000D_
_x000D_
  ];_x000D_
});
_x000D_
.pending-delete {_x000D_
  background-color: pink_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller='MyCtrl' ng-style="{color: myColor}">_x000D_
_x000D_
  <input type="text" ng-model="myColor" placeholder="enter a color name">_x000D_
_x000D_
  <div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">_x000D_
    name: {{item.name}}, {{item.title}}_x000D_
    <input type="checkbox" ng-model="item.checked" />_x000D_
    <span ng-show="item.checked"/><span>(will be deleted)</span>_x000D_
  </div>_x000D_
  <p>_x000D_
    <div ng-hide="myColor== 'red'">I will hide if the color is set to 'red'.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_