Programs & Examples On #System.web.ui.webcontrols

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

How to send email in ASP.NET C#

You can try MailKit MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices. You can use easily in your application.You can download from here.

                MimeMessage mailMessage = new MimeMessage();
                mailMessage.From.Add(new MailboxAddress(fromName, [email protected]));
                mailMessage.Sender = new MailboxAddress(senderName, [email protected]);
                mailMessage.To.Add(new MailboxAddress(emailid, emailid));
                mailMessage.Subject = subject;
                mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
                mailMessage.Subject = subject;
                var builder = new BodyBuilder();
                builder.TextBody = "Hello There";           
                try
                {
                    using (var smtpClient = new SmtpClient())
                    {
                        smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                        smtpClient.Authenticate("[email protected]", "password");

                        smtpClient.Send(mailMessage);
                        Console.WriteLine("Success");
                    }
                }
                catch (SmtpCommandException ex)
                {
                    Console.WriteLine(ex.ToString());              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());                
                }              

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

A potentially dangerous Request.Form value was detected from the client

You can HTML encode text box content, but unfortunately that won't stop the exception from happening. In my experience there is no way around, and you have to disable page validation. By doing that you're saying: "I'll be careful, I promise."

asp.net: Invalid postback or callback argument

This is probably not the cause of your issue, but I noticed you were using optgroups in your dropdown so I figured this might help someone should they wind up here with this issue. For me, I needed to create a dropdownlist that would render with optgroups, and I ended up using the accepted answer here but while it would render the control correctly, it gave me this error. How I got past that is detailed in my answer here.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Just keep the following in mind.

In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

How to hide a TemplateField column in a GridView

GridView1.Columns[columnIndex].Visible = false;

Cannot use a leading ../ to exit above the top directory

I moved my project from "standard" hosting to Azure and get the same error when I try to open page with url-rewrite. I.e. rule is :

<add key="/iPod-eBook-Creator.html" value="/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR" />

try to open my_site/iPod-eBook-Creator.html and get this error (page my_site/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR can be opened without any problem).

I checked the fully site - never used .. to "level up"

How to correctly use the ASP.NET FileUpload control

Instead of instantiating the FileUpload in your code behind file, just declare it in your markup file (.aspx file):

<asp:FileUpload ID="fileUpload" runat="server" />

Then you will be able to access all of the properties of the control, such as HasFile.

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

You can always refractor the namespace and it will update all the pages at the same time. Highlight the namespace, right click and select refractor from the drop down menu.

Parse JSON in C#

Thank you all for your help. This is my final version, and it works thanks to your combined help ! I am only showing the changes i made, all the rest is taken from Joe Chung's work

public class GoogleSearchResults
    {
        [DataMember]
        public ResponseData responseData { get; set; }

        [DataMember]
        public string responseDetails { get; set; }

        [DataMember]
        public int responseStatus { get; set; }
    }

and

 [DataContract]
    public class ResponseData
    {
        [DataMember]
        public List<Results> results { get; set; }
    }

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

You just need to return false from the

_x000D_
_x000D_
function jsFunction() {
  try {
    // Logic goes here
    return false; // true for postback and false for not postback
  } catch (e) {
    alert(e.message);
    return false;
  }
}
_x000D_
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />
_x000D_
_x000D_
_x000D_

JavaScript function like below.

Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.

How to make sure you don't get WCF Faulted state exception?

This error can also be caused by having zero methods tagged with the OperationContract attribute. This was my problem when building a new service and testing it a long the way.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.

This caused the app pool to give up and reply with the exception noted in the question.

How do I set Java's min and max heap size through environment variables?

A couple of notes:

  1. Apache ant doesn't know anything about JAVA_OPTS, while Tomcat's startup scripts do. For Apache ant, use ANT_OPTS to affect the environment for the JVM that runs /ant/, but not for the things that ant might launch.

  2. The maximum heap size you can set depends entirely on the environment: for most 32-bit systems, the maximum amount of heap space you can request, regardless of available memory, is in the 2GiB range. The largest heap on a 64-bit system is "really big". Also, you are practically limited by physical memory as well, since the heap is managed by the JVM and you don't want a lot of swapping going on to the disk.

  3. For server environments, you typically want to set -Xms and -Xmx to the same value: this will fix the size of the heap at a certain size and the garbage collector has less work to do because the heap will never have to be re-sized.

Clear contents of cells in VBA using column reference

You can access entire column as a range using the Worksheet.Columns object

Something like:

Worksheets(sheetname).Columns(1).ClearContents 

should clear contents of A column

There is also the Worksheet.Rows object if you need to do something similar for rows


The error you are receiving is likely due to a missing with block.

You can read about with blocks here: Microsoft Help

Multiple Cursors in Sublime Text 2 Windows

Mac Users, let me save you the time:

  • Cmd+a: select the lines you want a cursor
  • Cmd+Shift+l: to create the cursor

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

How to determine day of week by passing specific date?

Calendar class has build-in displayName functionality:

Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); // Thu   

Calendar.SHORT -> Thu
Calendar.LONG_FORMAT -> Thursday

Available since Java 1.6. See also Oracle documentation

Copy all values in a column to a new column in a pandas dataframe

The problem is in the line before the one that throws the warning. When you create df_2 that's where you're creating a copy of a slice of a dataframe. Instead, when you create df_2, use .copy() and you won't get that warning later on.

df_2 = df[df['B'] == 'b.2'].copy()

Fit cell width to content

I'm not sure if I understand your question, but I'll take a stab at it:

_x000D_
_x000D_
td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

Disable keyboard on EditText

I found this solution which works for me. It also places the cursor, when clicked on EditText at the correct position.

EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);   // handle the event first
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // hide the soft keyboard 
            }                
            return true;
        }
    });

How to remove trailing whitespace in code, using another script?

You don't see any output from the print statements because FileInput redirects stdout to the input file when the keyword argument inplace=1 is given. This causes the input file to effectively be rewritten and if you look at it afterwards the lines in it will indeed have no trailing or leading whitespace in them (except for the newline at the end of each which the print statement adds back).

If you only want to remove trailing whitespace, you should use rstrip() instead of strip(). Also note that the if lines == '': continue is causing blank lines to be completely removed (regardless of whether strip or rstrip gets used).

Unless your intent is to rewrite the input file, you should probably just use for line in open(filename):. Otherwise you can see what's being written to the file by simultaneously echoing the output to sys.stderr using something like the following:

import fileinput
import sys

for line in (line.rstrip() for line in
                fileinput.FileInput("test.txt", inplace=1)):
    if line:
        print line
        print >>sys.stderr, line

What to do with branch after merge

After the merge, it's safe to delete the branch:

git branch -d branch1

Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

If you also want to delete the branch on a remote host, you can do:

git push origin :branch1

This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).


git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

Maven Install on Mac OS X

  1. Open terminal
  2. Just use brew command to install maven
brew install maven
  1. After the download and install finished. Check for the maven version
mvn -version

Here you go !!! Now you have successfully installed maven on your mac os.

How do I split an int into its digits?

A simple answer to this question can be:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.

I Think It Will Help. I Used Simple Code Like:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}

Export to csv in jQuery

Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>        
        <script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {

 $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to CSV");
    $button.insertAfter($table);

    $button.click(function() {     
         CSV.begin('table').download('Export.csv').go();
    });
  });  
})

</script>
    </head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>      
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>        
    <td>94</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Doe</td>        
    <td>80</td>
  </tr>
</table>
</div>
</body>
</html>

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would point a beginner to the Wiki article on the Main function, then supplement it with this.

  • Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

Disable cache for some images

Simple, send one header location.

My site, contains one image, and after upload the image, there not change, then I add this code:

<?php header("Location: pagelocalimage.php"); ?>

Work's for me.

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

SQL Server Management Studio, how to get execution time down to milliseconds

I don't know about expanding the information bar.

But you can get the timings set as a default for all queries showing in the "Messages" tab.

When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.

You could also use Shift + Alt + S to enable client statistics at any time

Generating unique random numbers (integers) between 0 and 'x'

for(i = 0;i <amount; i++)
{
    var randomnumber=Math.floor(Math.random()*limit)+1
    document.write(randomnumber)
}

Vim: How to insert in visual block mode?

if you want to add new text before or after the selected colum:

  • press ctrl+v
  • select columns
  • press shift+i
  • write your text
  • press esc
  • press "jj"

Get a worksheet name using Excel VBA

This works for me.

worksheetName = ActiveSheet.Name  

How can I set the default timezone in node.js?

You could enforce the Node.js process timezone by setting the environment variable TZ to UTC

So all time will be measured in UTC+00:00

Full list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Example package.json:

{
  "scripts": {
    "start": "TZ='UTC' node index.js"
  }
}

The best way to remove duplicate values from NSMutableArray in Objective-C?

just use this simple code :

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

since nsset doesn't allow duplicate values and all objects returns an array

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Passing arguments to an interactive program non-interactively

You can put the data in a file and re-direct it like this:

$ cat file.sh
#!/bin/bash

read x
read y
echo $x
echo $y

Data for the script:

$ cat data.txt
2
3

Executing the script:

$ file.sh < data.txt
2
3

SQL update fields of one table from fields of another one

The question is old but I felt the best answer hadn't been given, yet.

Is there an UPDATE syntax ... without specifying the column names?

General solution with dynamic SQL

You don't need to know any column names except for some unique column(s) to join on (id in the example). Works reliably for any possible corner case I can think of.

This is specific to PostgreSQL. I am building dynamic code based on the the information_schema, in particular the table information_schema.columns, which is defined in the SQL standard and most major RDBMS (except Oracle) have it. But a DO statement with PL/pgSQL code executing dynamic SQL is totally non-standard PostgreSQL syntax.

DO
$do$
BEGIN

EXECUTE (
SELECT
  'UPDATE b
   SET   (' || string_agg(        quote_ident(column_name), ',') || ')
       = (' || string_agg('a.' || quote_ident(column_name), ',') || ')
   FROM   a
   WHERE  b.id = 123
   AND    a.id = b.id'
FROM   information_schema.columns
WHERE  table_name   = 'a'       -- table name, case sensitive
AND    table_schema = 'public'  -- schema name, case sensitive
AND    column_name <> 'id'      -- all columns except id
);

END
$do$;

Assuming a matching column in b for every column in a, but not the other way round. b can have additional columns.

WHERE b.id = 123 is optional, to update a selected row.

SQL Fiddle.

Related answers with more explanation:

Partial solutions with plain SQL

With list of shared columns

You still need to know the list of column names that both tables share. With a syntax shortcut for updating multiple columns - shorter than what other answers suggested so far in any case.

UPDATE b
SET   (  column1,   column2,   column3)
    = (a.column1, a.column2, a.column3)
FROM   a
WHERE  b.id = 123    -- optional, to update only selected row
AND    a.id = b.id;

SQL Fiddle.

This syntax was introduced with Postgres 8.2 in 2006, long before the question was asked. Details in the manual.

Related:

With list of columns in B

If all columns of A are defined NOT NULL (but not necessarily B),
and you know the column names of B (but not necessarily A).

UPDATE b
SET   (column1, column2, column3, column4)
    = (COALESCE(ab.column1, b.column1)
     , COALESCE(ab.column2, b.column2)
     , COALESCE(ab.column3, b.column3)
     , COALESCE(ab.column4, b.column4)
      )
FROM (
   SELECT *
   FROM   a
   NATURAL LEFT JOIN  b -- append missing columns
   WHERE  b.id IS NULL  -- only if anything actually changes
   AND    a.id = 123    -- optional, to update only selected row
   ) ab
WHERE b.id = ab.id;

The NATURAL LEFT JOIN joins a row from b where all columns of the same name hold same values. We don't need an update in this case (nothing changes) and can eliminate those rows early in the process (WHERE b.id IS NULL).
We still need to find a matching row, so b.id = ab.id in the outer query.

db<>fiddle here
Old sqlfiddle.

This is standard SQL except for the FROM clause.
It works no matter which of the columns are actually present in A, but the query cannot distinguish between actual NULL values and missing columns in A, so it is only reliable if all columns in A are defined NOT NULL.

There are multiple possible variations, depending on what you know about both tables.

How to know elastic search installed version from kibana?

I would like to add which isn't mentioned in above answers.

From your kibana's dev console, hit following command:

GET /

This is similar to accessing localhost:9200 from browser.

Hope this will help someone.

How to Test Facebook Connect Locally

Edit your app at www.facebook.com/developers/ and set the "Site URL" to "http://localhost/myapppath".

When done - change it back.

How to change Screen buffer size in Windows Command Prompt from batch script

mode con lines=32766

sets the buffer, but also increases the window height to full screen, which is ugly.

You can change the settings directly in the registry :

:: escape the environment variable in the key name
set mySysRoot=%%SystemRoot%%

:: 655294544 equals 9999 lines in the GUI
reg.exe add "HKCU\Console\%mySysRoot%_system32_cmd.exe" /v ScreenBufferSize /t REG_DWORD /d 655294544 /f

:: We also need to change the Window Height, 3276880 = 50 lines
reg.exe add "HKCU\Console\%mySysRoot%_system32_cmd.exe" /v WindowSize /t REG_DWORD /d 3276880 /f

The next cmd.exe you start has the increase buffer.

So this doesn't work for the cmd.exe you are already in, but just use this in a pre-batch.cmd which than calls your main script.

open_basedir restriction in effect. File(/) is not within the allowed path(s):

Modify the open_basedir settings in your hosting account and set them to none. Find the open_basedir setting given under 'PHP Settings' area of your Plesk/cPanel. Set it to 'none' from the dropdown given there. I have shown them in the Plesk panel picture.

enter image description here enter image description here

How to convert array into comma separated string in javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

_x000D_
_x000D_
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
_x000D_
_x000D_

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

Broadcast receiver for checking internet connection in android app

Checking internet status every time using Broadcast Receiver:

internet status implementation

Full source code available on Google Drive.

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<receiver android:name=".receivers.NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
</receiver>

BroadcastReciever

package com.keshav.networkchangereceiverexample.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import static com.keshav.networkchangereceiverexample.MainActivity.dialog;

public class NetworkChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            if (isOnline(context)) {
                dialog(true);
                Log.e("keshav", "Online Connect Intenet ");
            } else {
                dialog(false);
                Log.e("keshav", "Conectivity Failure !!! ");
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    private boolean isOnline(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            //should check null because in airplane mode it will be null
            return (netInfo != null && netInfo.isConnected());
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }
}

MainActivity.java

package com.keshav.networkchangereceiverexample;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.keshav.networkchangereceiverexample.receivers.NetworkChangeReceiver;

public class MainActivity extends AppCompatActivity {

    private BroadcastReceiver mNetworkReceiver;
    static TextView tv_check_connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
        mNetworkReceiver = new NetworkChangeReceiver();
        registerNetworkBroadcastForNougat();

    }

    public static void dialog(boolean value){

        if(value){
            tv_check_connection.setText("We are back !!!");
            tv_check_connection.setBackgroundColor(Color.GREEN);
            tv_check_connection.setTextColor(Color.WHITE);

            Handler handler = new Handler();
            Runnable delayrunnable = new Runnable() {
                @Override
                public void run() {
                    tv_check_connection.setVisibility(View.GONE);
                }
            };
            handler.postDelayed(delayrunnable, 3000);
        }else {
            tv_check_connection.setVisibility(View.VISIBLE);
            tv_check_connection.setText("Could not Connect to internet");
            tv_check_connection.setBackgroundColor(Color.RED);
            tv_check_connection.setTextColor(Color.WHITE);
        }
    }


    private void registerNetworkBroadcastForNougat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

    protected void unregisterNetworkChanges() {
        try {
            unregisterReceiver(mNetworkReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterNetworkChanges();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.keshav.networkchangereceiverexample.MainActivity">

    <TextView
        android:id="@+id/tv_check_connection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Connection establised !"
        android:padding="25dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:gravity="center"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

"echo -n" prints "-n"

There are multiple versions of the echo command, with different behaviors. Apparently the shell used for your script uses a version that doesn't recognize -n.

The printf command has much more consistent behavior. echo is fine for simple things like echo hello, but I suggest using printf for anything more complicated.

What system are you on, and what shell does your script use?

JPA Query selecting only specific columns without using Criteria Query?

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

Examples can be found in this article.

UPDATE 29.03.2018:

@Krish:

@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

Play audio file from the assets directory

Fix of above function for play and pause

  public void playBeep ( String word )
{
    try
    {
        if ( ( m == null ) )
        {

            m = new MediaPlayer ();
        }
        else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
            m.stop();
            m.release ();
            m=null;
            lastPlayed="";
            return;
        }else if(m != null){
            m.release ();
            m = new MediaPlayer ();
        }
        lastPlayed=word;

        AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
        long                start      = descriptor.getStartOffset ();
        long                end        = descriptor.getLength ();

        // get title
        // songTitle=songsList.get(songIndex).get("songTitle");
        // set the data source
        try
        {
            m.setDataSource ( descriptor.getFileDescriptor (), start, end );
        }
        catch ( Exception e )
        {
            Log.e ( "MUSIC SERVICE", "Error setting data source", e );
        }

        m.prepare ();
        m.setVolume ( 1f, 1f );
        // m.setLooping(true);
        m.start ();
    }
    catch ( Exception e )
    {
        e.printStackTrace ();
    }
}

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

How to remove an unpushed outgoing commit in Visual Studio?

I fixed it in Github Desktop Application by pushing my changes.

Convert List<Object> to String[] in Java

Java 8 has the option of using streams like:

List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);

Web scraping with Java

You might look into jwht-scrapper!

This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:

It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.

Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!

Hope this might help some people here!

Disclaimer, I am the one who developed it, feel free to let me know your remarks!

Create Carriage Return in PHP String?

Carriage return is "\r". Mind the double quotes!

I think you want "\r\n" btw to put a line break in your text so it will be rendered correctly in different operating systems.

  • Mac: \r
  • Linux/Unix: \n
  • Windows: \r\n

android: how to align image in the horizontal center of an imageview?

You can center the ImageView itself by using:

android:layout_centerVertical="true" or android:layout_centerHorizontal="true" For vertical or horizontal. Or to center inside the parent:

android:layout_centerInParent="true"

But it sounds like you are trying to center the actual source image inside the imageview itself, which I am not sure on.

How to deal with missing src/test/java source folder in Android/Maven project?

Select project -> New -> Folder (not source folder) -> Select the project again -> Enter the folder name as (src/test/java) -> finish. That's it.

If the test source is missing, it would link it automatically. If not, then require to link it manually.

How to secure phpMyAdmin

The best way to secure phpMyAdmin is the combination of all these 4:

1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)

Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:

# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):

    sudo nano /etc/apache2/conf-available/phpmyadmin.conf
            /etc/phpmyadmin/apache.conf
        Change: phpmyadmin URL by this line:
            Alias /newphpmyadminname /usr/share/phpmyadmin
        Add: AllowOverride All
            <Directory /usr/share/phpmyadmin>
                Options FollowSymLinks
                DirectoryIndex index.php
                AllowOverride Limit
                ...
        sudo systemctl restart apache2
        sudo nano /usr/share/phpmyadmin/.htaccess
            deny from all
            allow from 127.0.0.1

        alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
        alias myip="echo ${SSH_CONNECTION%% *}"

# Secure Web Access to phpMyAdmin:

        Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
            https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04

        PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add

        C:\Windows\System32\drivers\etc
            Notepad - Run As Administrator - open: hosts
                127.0.0.1 pma.yourdomain.com

        https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
        https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)

        # Check to make sure you are on SSH Tunnel
            1. Windows - CMD:
                ping pma.yourdomain.com
                ping www.yourdomain.com

                # See PuTTY ports:
                netstat -ano |find /i "listening"

            2. Test live:
                https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/

If you are able to do these all successfully,

you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.

Given final block not properly padded

This can also be a issue when you enter wrong password for your sign key.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I had a similar situation on Mac, and the following process worked for me:

In the terminal, type

vi ~/.profile

Then add this line in the file, and save

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home

where version is the one on your computer, such as 1.7.0_25.

Exit the editor, then type the following command make it become effective

source ~/.profile 

Then type java -version to check the result

java -version 

What is .profile file?

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

Source: http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

Is it really impossible to make a div fit its size to its content?

you can also use

word-break: break-all;

when nothing seems working this works always ;)

How to create an empty file at the command line in Windows?

Try this:

type NUL > 1.txt

this will definitely create an empty file.

Address already in use: JVM_Bind java

The quick answer on how to prevent it is that you most likely need to stop JBoss before starting it again.

You should be able to call the "Terminate" button in the Console view to shutdown the server.

How to read a single character at a time from a file in Python?

To make a supplement, if you are reading file that contains a line that is vvvvery huge, which might break your memory, you might consider read them into a buffer then yield the each char

def read_char(inputfile, buffersize=10240):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(buffersize)
            if not buf:
                break
            for char in buf:
                yield char
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_char('./very_large_file.txt'):
        process(char)

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

Jupyter Notebook not saving: '_xsrf' argument missing from post

I use jupyter notebooks daily and had never experienced this issue before... until today. I had the notebook open all day but it wasn't running anything and then for no apparent reason stopped auto-saving with the '_xsrf' argument missing from POST error message in the top right. FYI - this is a python3 notebook.

I don't know the cause of this problem but I have recently upgraded my python3 version to 3.7.2 and upgraded all of my site-packages to their latest version as of a few days ago which could possibly be the cause.

As for a solution, as suggested in the comment by @AlexK, I opened the same notebook in a new window (different browser in fact), using

jupyter notebook list

in the terminal to get the URL with login token.

This resulted in me having the notebook open and savable again but the information I had entered since the last successful auto-save was missing. Thankfully, my broken instance was still open and working apart from saving so I was able to simply copy and paste the information across then hit save. So, keep the broken instance open if you try this!

Eloquent ->first() if ->exists()

An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.

    try {
        $user = User::where('mobile', Input::get('mobile'))->first();
    } catch (ErrorException $e) {
        // Do stuff here that you need to do if it doesn't exist.
        return View::make('some.view')->with('msg', $e->getMessage());
    }

MVC4 input field placeholder

You can easily add Css class, placeholder , etc. as shown below:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder="Name" })

Hope this helps

how to output every line in a file python

Firstly, as @l33tnerd said, f.close should be outside the for loop.

Secondly, you are only calling readline once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:

 if data.find('!masters') != -1:
     f = open('masters.txt')
     for line in f:
           print line,
           sck.send('PRIVMSG ' + chan + " " + line)
     f.close()

Finally, you were referring to the variable lines inside the loop; I assume you meant to refer to line.

Edit: Oh and you need to indent the contents of the if statement.

Virtual Memory Usage from Java under Linux, too much memory used

This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.

java -Xms1024m -Xmx4096m com.example.Hello

Different Ways to Measure Memory

On Linux, the top command gives you several different numbers for memory. Here's what it says about the Hello World example:

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 2120 kgregory  20   0 4373m  15m 7152 S    0  0.2   0:00.10 java
  • VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
  • RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
  • SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
  • SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, whether or not it's actually in the swap space. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.

The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the official documentation is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually documented. Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.

Understanding the Virtual Memory Map

The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the pmap command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.

0000000040000000     36K r-x--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000      8K rwx--  /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000    676K rwx--    [ anon ]
00000006fae00000  21248K rwx--    [ anon ]
00000006fc2c0000  62720K rwx--    [ anon ]
0000000700000000 699072K rwx--    [ anon ]
000000072aab0000 2097152K rwx--    [ anon ]
00000007aaab0000 349504K rwx--    [ anon ]
00000007c0000000 1048576K rwx--    [ anon ]
...
00007fa1ed00d000   1652K r-xs-  /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000   1024K rwx--    [ anon ]
00007fa1ed2d3000      4K -----    [ anon ]
00007fa1ed2d4000   1024K rwx--    [ anon ]
00007fa1ed3d4000      4K -----    [ anon ]
...
00007fa1f20d3000    164K r-x--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000   1020K -----  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000     28K rwx--  /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000   1576K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000   2044K -----  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000     16K r-x--  /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000      4K rwx--  /lib/x86_64-linux-gnu/libc-2.13.so
...

A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via mmap.

Starting from the top, we have

  • The JVM loader (ie, the program that gets run when you type java). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
  • A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the -Xmx value; this allows it to have a contiguous heap. The -Xms value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
  • A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
  • Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a StackOverFlowError. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
  • One of the shared libraries that holds the actual JVM code. There are several of these.
  • The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.

The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, libc has 1.5M of virtual memory space that can be shared.

When is Virtual Memory Size Important?

The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.

Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.

But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.

When is Resident Set Size Important?

Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.

But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.

Bottom Line

Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.

With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.

Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so.

How to use a variable in the replacement side of the Perl substitution operator?

On the replacement side, you must use $1, not \1.

And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:

$find="start (.*) end";
$replace='"foo $1 bar"';

$var = "start middle end";
$var =~ s/$find/$replace/ee;

print "var: $var\n";

To see why the "" and double /e are needed, see the effect of the double eval here:

$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar

(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval(); rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...)) still demonstrates why you need to do what you need to do to get /ee to work as desired.)

How to send POST request?

If you need your script to be portable and you would rather not have any 3rd party dependencies, this is how you send POST request purely in Python 3.

from urllib.parse import urlencode
from urllib.request import Request, urlopen

url = 'https://httpbin.org/post' # Set destination URL here
post_fields = {'foo': 'bar'}     # Set POST fields here

request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)

Sample output:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "foo": "bar"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "7", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.3"
  }, 
  "json": null, 
  "origin": "127.0.0.1", 
  "url": "https://httpbin.org/post"
}

How to set custom favicon in Express?

smiley favicon to prevent error:

 //const fs = require('fs'); 
 //const favicon = fs.readFileSync(__dirname+'/public/favicon.ico'); // read file
 const favicon = new Buffer.from('AAABAAEAEBAQAAAAAAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA/4QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEREQAAAAAAEAAAEAAAAAEAAAABAAAAEAAAAAAQAAAQAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAA//8AAP//AAD8HwAA++8AAPf3AADv+wAA7/sAAP//AAD//wAA+98AAP//AAD//wAA//8AAP//AAD//wAA', 'base64'); 
 app.get("/favicon.ico", function(req, res) {
  res.statusCode = 200;
  res.setHeader('Content-Length', favicon.length);
  res.setHeader('Content-Type', 'image/x-icon');
  res.setHeader("Cache-Control", "public, max-age=2592000");                // expiers after a month
  res.setHeader("Expires", new Date(Date.now() + 2592000000).toUTCString());
  res.end(favicon);
 });

to change icon in code above

make an icon maybe here: http://www.favicon.cc/ or here :http://favicon-generator.org

convert it to base64 maybe here: http://base64converter.com/

then replace the icon base 64 value

general information how to create a personalized fav icon

icons are made using photoshop or inkscape, maybe inkscape then photoshop for vibrance and color correction (in image->adjustments menu).

for quick icon goto http://www.clker.com/ and pick some Vector Clip Arts, and download as svg. then bring it to inkscape (https://inkscape.org/) and change colors or delete parts, maybe add something from another vector clipart image, then to export select the parts to export and click file>export, pick size like 16x16 for favicon or 32x32. for further edit 128x128 or 256x256. ico package can have several icon sizes inside. it can have along with 16x16 pixel favicon a high quality icons for link for the website.

then maybe enhance the image in photoshop. like vibrance, bevel effect, round mask, anything.

then upload this image to one of the websites that generate favicons. there are also programs for windows for editing icons like https://sourceforge.net/projects/variicons/ .

to add the favicon to website. just put the favicon.ico as a file in the root folder of the domain. for example in node.js in public folder that contains the static files. it doesn't have to be anything special like code above just a simple file.

Search of table names

I am assuming you want to pass the database name as a parameter and not just run:

SELECT  *
FROM    DBName.sys.tables
WHERE   Name LIKE '%XXX%'

If so, you could use dynamic SQL to add the dbname to the query:

DECLARE @DBName NVARCHAR(200) = 'YourDBName',
        @TableName NVARCHAR(200) = 'SomeString';

IF NOT EXISTS (SELECT 1 FROM master.sys.databases WHERE Name = @DBName)
    BEGIN
        PRINT 'DATABASE NOT FOUND';
        RETURN;
    END;

DECLARE @SQL NVARCHAR(MAX) = '  SELECT  Name
                                FROM    ' + QUOTENAME(@DBName) + '.sys.tables
                                WHERE   Name LIKE ''%'' + @Table + ''%''';

EXECUTE SP_EXECUTESQL @SQL, N'@Table NVARCHAR(200)', @TableName;

How to run batch file from network share without "UNC path are not supported" message?

My situation is just a little different. I'm running a batch file on startup to distribute the latest version of internal business applications.

In this situation I'm using the Windows Registry Run Key with the following string

cmd /c copy \\serverName\SharedFolder\startup7.bat %USERPROFILE% & %USERPROFILE%\startup7.bat

This runs two commands on startup in the correct sequence. First copying the batch file locally to a directory the user has permission to. Then executing the same batch file. I can create a local directory c:\InternalApps and copy all of the files from the network.

This is probably too late to solve the original poster's question but it may help someone else.

Sending an HTTP POST request on iOS

Sending an HTTP POST request on iOS (Objective c):

-(NSString *)postexample{

// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

//RESPONDE DATA 
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];

return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}

How can I reference a commit in an issue comment on GitHub?

To reference a commit, simply write its SHA-hash, and it'll automatically get turned into a link.

See also:

Is there any way to change input type="date" format?

Browsers obtain the date-input format from user's system date format.

(Tested in supported browsers, Chrome, Edge.)

As there is no standard defined by specs as of now to change the style of date control, its not possible to implement the same in browsers.

Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system's setting. Web authors have no way to change the date format because there currently is no standards to specify the format.

So no need to change it, if we don't change anything, users will see the date-input's format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.

Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.

Refer google developers page on same.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.

Example

node('label'){
    // now you are on slave labeled with 'label'
    def workspace = WORKSPACE
    // ${workspace} will now contain an absolute path to job workspace on slave

    workspace = env.WORKSPACE
    // ${workspace} will still contain an absolute path to job workspace on slave

    // When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
    echo "Current workspace is ${env.WORKSPACE}"

    // the current Jenkins instances will support the short syntax, too:
    echo "Current workspace is $WORKSPACE"

}

filename.whl is not supported wheel on this platform

I am using Python2.7 and Windows 64-bit system. I was getting the same error for lxml-3.8.0-cp27-cp27m-win_amd64.whl while doing pip install lxml-3.8.0-cp27-cp27m-win_amd64.whl Run pip install lxml and it auto-detected and successfully installed the win32 version (though my system is Windows-64bit)

C:\Python27>pip install lxml
Collecting lxml
  Downloading lxml-3.8.0-cp27-cp27m-win32.whl (2.9MB)
    100% |################################| 2.9MB 20kB/s
Installing collected packages: lxml
Successfully installed lxml-3.8.0

So, I will go with @1man's answer.

How to scroll UITableView to specific position

it should work using - (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated using it this way:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[yourTableView scrollToRowAtIndexPath:indexPath 
                     atScrollPosition:UITableViewScrollPositionTop 
                             animated:YES];

atScrollPosition could take any of these values:

typedef enum {
UITableViewScrollPositionNone,
UITableViewScrollPositionTop,
UITableViewScrollPositionMiddle,
UITableViewScrollPositionBottom
} UITableViewScrollPosition;

I hope this helps you

Cheers

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

I also experienced this cmderror. After trying all the answers on here, I couldn't still figure out the problem, here is what I did:

  1. Cd into the project directory. e.g cd project-dir
  2. I migrated. e.g python manage.py migrate
  3. I created a super user. e.g python manage.py createsuperuser
  4. Enter the desired info like username, password, email etc
  5. You should get a "super user created successfully" response
  6. Now run the server. E.g python manage.py runserver
  7. Click on the URL displayed
  8. The URL on your browser should look like this, 127.0.0.1:8000/Quit
  9. Now edit the URL on your browser to this, 127.0.0.1:8000/admin
  10. You should see an administrative login page
  11. Login with the super user info you created earlier on
  12. You should be logged in to the Django administration
  13. Now click on "view site" at the top of the page
  14. You should see a page which shows "the install worked successfully..... Debug = True"
  15. Voila! your server is up and running

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

How do I update zsh to the latest version?

If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):

  1. Get the latest version of the ZSH sourcecode

  2. Untar the download into its own directory then install: ./configure && make && make test && sudo make install

  3. This installs the the zsh binary at /usr/local/bin/zsh.

  4. You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...

  5. To make it your default shell you must first edit /etc/shells and add the new path. Then you can either run chsh -s /usr/local/bin/zsh or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".

  6. Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).

I want to get the type of a variable at runtime

i have tested that and it worked

val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}

Bash: Strip trailing linebreak from output

If you want to print output of anything in Bash without end of line, you echo it with the -n switch.

If you have it in a variable already, then echo it with the trailing newline cropped:

$ testvar=$(wc -l < log.txt)
$ echo -n $testvar

Or you can do it in one line, instead:

$ echo -n $(wc -l < log.txt)

Javascript dynamic array of strings

As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9,10,11


var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9

You can even add elements like

var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

you can even change the values

myArray[2] = 40

Printing Order

If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.

Page Submission

If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

Fit website background image to screen size

Try this:

background: url(../IMAGES/background.jpg) no-repeat;
background-size: auto auto;

How to set session timeout in web.config

If it's not working from web.config, you need to set it from IIS.

How to set the max size of upload file

None of the configuration above worked for me with a Spring application.

Implementing this code in the main application class (the one annotated with @SpringBootApplication) did the trick.

@Bean 
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
     return (ConfigurableEmbeddedServletContainer container) -> {

              if (container instanceof TomcatEmbeddedServletContainerFactory) {

                  TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
                  tomcat.addConnectorCustomizers(
                          (connector) -> {
                              connector.setMaxPostSize(10000000);//10MB
                          }
                  );
              }
    };
}

You can change the accepted size in the statement:

connector.setMaxPostSize(10000000);//10MB

How do I get the day month and year from a Windows cmd.exe script?

I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.

Here is how to get the day, month, and year

for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i

Or, here is yesterday's date in yyyy-MM-dd format

for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i

Day of the week

for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d

Current time plus 15 minutes

for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

window.location.href and window.open () methods in JavaScript

window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.

Better way to cast object to int

Maybe Convert.ToInt32.

Watch out for exception, in both cases.

What's NSLocalizedString equivalent in Swift?

In addition to great extension written here if you are lazy to find and replace old NSLocalizedString you can open find & replace in Xcode and in the find section you can write NSLocalizedString\(\(".*"\), comment: ""\) then in the replace section you need to write $1.localized to change all NSLocalizedString with "blabla".localized in your project.

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Difference between setTimeout with and without quotes and parentheses

What happens in reality in case you pass string as a first parameter of function

setTimeout('string',number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

setTimeout(eval('string'), number)

This is

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

So samples which you refer are not good samples, and may be given in different context or just simple typo.

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

"inconsistent use of tabs and spaces in indentation"

If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces ? choose Anaconda ? click on autoformat. Done. Or press Ctrl + Alt + R.

Start an Activity with a parameter

Kotlin code:

Start the SecondActivity:

startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

Get the Id in SecondActivity:

class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

where gameId is String? (can be null)

bash string compare to multiple correct values

Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

Split string into strings by length?

Got an re trick:

In [28]: import re

In [29]: x = "qwertyui"

In [30]: [x for x in re.split(r'(\w{2})', x) if x]
Out[30]: ['qw', 'er', 'ty', 'ui']

Then be a func, it might looks like:

def split(string, split_len):
    # Regex: `r'.{1}'` for example works for all characters
    regex = r'(.{%s})' % split_len
    return [x for x in re.split(regex, string) if x]

How do you debug PHP scripts?

I use Netbeans with XDebug. Check it out at its website for docs on how to configure it. http://php.netbeans.org/

Create Elasticsearch curl query for not null and not empty("")

You can use not filter on top of missing.

"query": {
  "filtered": {
     "query": {
        "match_all": {}
     },
     "filter": {
        "not": {
           "filter": {
              "missing": {
                 "field": "searchField"
              }
           }
        }
     }
  }
}

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

Foreign Key naming scheme

The standard convention in SQL Server is:

FK_ForeignKeyTable_PrimaryKeyTable

So, for example, the key between notes and tasks would be:

FK_note_task

And the key between tasks and users would be:

FK_task_user

This gives you an 'at a glance' view of which tables are involved in the key, so it makes it easy to see which tables a particular one (the first one named) depends on (the second one named). In this scenario the complete set of keys would be:

FK_task_user
FK_note_task
FK_note_user

So you can see that tasks depend on users, and notes depend on both tasks and users.

Storing WPF Image Resources

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

phpMyAdmin - Error > Incorrect format parameter?

For me, adjusting the 2 values was not enough. If the file is too big, you also need to adjust the execution time variables.

First, ../php/php.ini

upload_max_filesize=128M
post_max_size=128M
max_execution_time=1000

Then, ../phpMyAdmin\libraries\config.default.php

$cfg['ExecTimeLimit'] = 1000;

This did the trick for me. The variables can be choosen differently of course. Maybe the execution time has to be even higher. And the size depends on your filesize.

Is there an easy way to strike through text in an app widget?

For doing this you can use this

 title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

and for remove you can use this

 title.setPaintFlags(title.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));

How to SHUTDOWN Tomcat in Ubuntu?

Try

/etc/init.d/tomcat stop

(maybe you have to write something after tomcat, just press tab one time)

Edit: And you also need to do it as root.

How to import a module given its name as string?

If you want it in your locals:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

same would work with globals()

Authentication versus Authorization

Authentication is the process of ascertaining that somebody really is who they claim to be.

Authorization refers to rules that determine who is allowed to do what. E.g. Adam may be authorized to create and delete databases, while Usama is only authorised to read.

The two concepts are completely orthogonal and independent, but both are central to security design, and the failure to get either one correct opens up the avenue to compromise.

In terms of web apps, very crudely speaking, authentication is when you check login credentials to see if you recognize a user as logged in, and authorization is when you look up in your access control whether you allow the user to view, edit, delete or create content.

Check whether variable is number or string in JavaScript

Try this,

<script>
var regInteger = /^-?\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>

How can I use external JARs in an Android project?

If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):

  1. Select the Project view in the Project sideview (instead of Packages or Android)
  2. Create a folder called libs in your project's root folder
  3. Copy your JAR files to the libs folder
  4. The sideview will be updated and the JAR files will show up in your project
  5. Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
  6. After that, all you need to do is reference the new classes in your code, eg. import javax.mail.*

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Check if pull needed in Git

Run git fetch (remote) to update your remote refs, it'll show you what's new. Then, when you checkout your local branch, it will show you whether it's behind upstream.

How to actually search all files in Visual Studio

One can access the "Find in Files" window via the drop-down menu selection and search all files in the Entire Solution: Edit > Find and Replace > Find in Files

enter image description here

Other, alternative is to open the "Find in Files" window via the "Standard Toolbars" button as highlighted in the below screen-short:

enter image description here

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

Detect IE version (prior to v9) in JavaScript

According to Microsoft, following is the best solution, it is also very simple:

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if ( ver > -1 )
    {
        if ( ver >= 8.0 ) 
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
      }
    alert( msg );
}

MSVCP120d.dll missing

Alternate approach : without installation of Redistributable package.

Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.

you can download and use them in your project , I have used and run them successfully.

example : https://github.com/Emotiv/community-sdk/find/master

How to check for file lock?

You can see if the file is locked by trying to read or lock it yourself first.

Please see my answer here for more information.

Meaning of = delete after function declaration

Are there any other "modifiers" (other than = 0 and = delete)?

Since it appears no one else answered this question, I should mention that there is also =default.

https://docs.microsoft.com/en-us/cpp/cpp/explicitly-defaulted-and-deleted-functions#explicitly-defaulted-functions

Resolve build errors due to circular dependency amongst classes

I've written a post about this once: Resolving circular dependencies in c++

The basic technique is to decouple the classes using interfaces. So in your case:

//Printer.h
class Printer {
public:
    virtual Print() = 0;
}

//A.h
#include "Printer.h"
class A: public Printer
{
    int _val;
    Printer *_b;
public:

    A(int val)
        :_val(val)
    {
    }

    void SetB(Printer *b)
    {
        _b = b;
        _b->Print();
    }

    void Print()
    {
        cout<<"Type:A val="<<_val<<endl;
    }
};

//B.h
#include "Printer.h"
class B: public Printer
{
    double _val;
    Printer* _a;
public:

    B(double val)
        :_val(val)
    {
    }

    void SetA(Printer *a)
    {
        _a = a;
        _a->Print();
    }

    void Print()
    {
        cout<<"Type:B val="<<_val<<endl;
    }
};

//main.cpp
#include <iostream>
#include "A.h"
#include "B.h"

int main(int argc, char* argv[])
{
    A a(10);
    B b(3.14);
    a.Print();
    a.SetB(&b);
    b.Print();
    b.SetA(&a);
    return 0;
}

Python Binomial Coefficient

For Python 3, scipy has the function scipy.special.comb, which may produce floating point as well as exact integer results

import scipy.special

res = scipy.special.comb(x, y, exact=True)

See the documentation for scipy.special.comb.

For Python 2, the function is located in scipy.misc, and it works the same way:

import scipy.misc

res = scipy.misc.comb(x, y, exact=True)

How can I view an object with an alert()

Try this:

alert(JSON.parse(product) );

command/usr/bin/codesign failed with exit code 1- code sign error

If nothing is working in @d4Rk solution Just use the below screen to delete unwanted/expired similar provision profiles. Right click on provision profile to move it to trash. provision profile window

Because in my case after doing all the steps I was still getting the same issue and it resolved when I deleted old expired provision profiles with same name and then using the correct one in build setting.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html

Specifically:

Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.

I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.

Add a UIView above all, even the navigation bar

Note if you want add view in Full screen then only use below code

Add these extension of UIViewController

public extension UIViewController {
   internal func makeViewAsFullScreen() {
      var viewFrame:CGRect = self.view.frame
      if viewFrame.origin.y > 0 || viewFrame.origin.x > 0 {
        self.view.frame = UIScreen.main.bounds
      }
   }
}

Continue as normal adding process of subview

Now use in adding UIViewController's viewDidAppear

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

     self.makeViewAsFullScreen()
}

How to check the exit status using an if statement

Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then
    echo command returned true
else
    echo command returned some error
fi

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:

values/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>


values-v21/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:

    <activity
            android:name=".MyTransparentActionbarActivity"
            android:theme="@style/AppTheme.ActionBar.Transparent"/>

    <activity
            android:name=".MyColoredActionbarActivity"
            android:theme="@style/AppTheme.ActionBar"/>

enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.



Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

SOLUTION ONE:
Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:

    ...
        <LinearLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </LinearLayout>
    ...

SOLUTION TWO:
Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(R.id.bellow_actionbar);
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
        }

        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

Where R.id.bellow_actionbar will be the layout container view id of whatever we want to be placed bellow the Actionbar:

...
    <LinearLayout
            android:id="@+id/bellow_actionbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        ...
    </LinearLayout>
...

enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayUseLogoEnabled(false);
        }
        setStatusBarTranslucent(true);
    }

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

A general tree implementation?

A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

Then interact:

>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
...   print c.data
... 
6
7
>>> 

This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.

Return Result from Select Query in stored procedure to a List

Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = "it.hurts.when.IP";
            builder.UserID = "someDBUser";
            builder.Password = "someDBPassword";
            builder.InitialCatalog = "someDB";
            return new SqlConnection(builder.ConnectionString);
        }

        public static List<T> ExecuteSP<T>(string SPName, List<SqlParameter> Params)
        {
            try
            {
                DataTable dataTable = new DataTable();

                using (SqlConnection Connection = getConnectionString())
                {
                    // Open connection
                    Connection.Open();

                    // Create command from params / SP
                    SqlCommand cmd = new SqlCommand(SPName, Connection);

                    // Add parameters
                    cmd.Parameters.AddRange(Params.ToArray());
                    cmd.CommandType = CommandType.StoredProcedure;

                    // Make datatable for conversion
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dataTable);
                    da.Dispose();

                    // Close connection
                    Connection.Close();
                }

                // Convert to list of T
                var retVal = ConvertToList<T>(dataTable);
                return retVal;
            }
            catch (SqlException e)
            {
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

        /// <summary>
        /// Converts datatable to List<someType> if possible.
        /// </summary>
        public static List<T> ConvertToList<T>(DataTable dt)
        {
            try // Necesarry unfotunately.
            {
                var columnNames = dt.Columns.Cast<DataColumn>()
                    .Select(c => c.ColumnName)
                    .ToList();

                var properties = typeof(T).GetProperties();

                return dt.AsEnumerable().Select(row =>
                    {
                        var objT = Activator.CreateInstance<T>();

                        foreach (var pro in properties)
                        {
                            if (columnNames.Contains(pro.Name))
                            {
                                if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                else pro.SetValue(objT, row[pro.Name], null);
                            }
                        }

                        return objT;
                    }).ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                Console.WriteLine("ConvertToList Exception: " + e.ToString());
                return new List<T>();
            }
        }

Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

PostgreSQL - fetch the row which has the Max value for a column

I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col) and GROUP BY the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY plus LIMIT 1 instead (as done by Quassnoi):

SELECT * 
FROM lives outer
WHERE (usr_id, time_stamp, trans_id) IN (
    SELECT usr_id, time_stamp, trans_id
    FROM lives sq
    WHERE sq.usr_id = outer.usr_id
    ORDER BY trans_id, time_stamp
    LIMIT 1
)

I find using the row-constructor syntax WHERE (a, b, c) IN (subquery) nice because it cuts down on the amount of verbiage needed.

How to implement a lock in JavaScript

Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:

var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
    if (functionLock) {
        functionCallbacks.push(callback);
    } else {
        $.longRunning(function(response) {
             while(functionCallbacks.length){
                 var thisCallback = functionCallbacks.pop();
                 thisCallback(response);
             }
        });
    }
}

You can also implement this using DOM event listeners or a pubsub solution.

Android draw a Horizontal line between views

----> Simple one

 <TextView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#c0c0c0"
    android:id="@+id/your_id"
    android:layout_marginTop="160dp" />

Why doesn't Java support unsigned ints?

I can think of one unfortunate side-effect. In java embedded databases, the number of ids you can have with a 32bit id field is 2^31, not 2^32 (~2billion, not ~4billion).

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

symfony 2 twig limit the length of the text and put three dots

It is better to use an HTML character

{{ entity.text[:50] }}&#8230;

Get HTML inside iframe using jQuery

var iframe = document.getElementById('iframe');
  $(iframe).contents().find("html").html();

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

Unknown92 answer helped me (on windows). Note that all versions must fit.

I've downloaded cx_Oracle here, for me the file cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe worked with:

  • Python 3.5.1 64bit. for some reason the default download link from the main page is for the 32bit version.
  • And oracle instance client 12.1.0.2.0 (the file named instantclient-basic-windows.x64-12.1.0.2.0.zip) here.

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Outline effect to text

There is an experimental webkit property called text-stroke in CSS3, I've been trying to get this to work for some time but have been unsuccessful so far.

What I have done instead is used the already supported text-shadow property (supported in Chrome, Firefox, Opera, and IE 9 I believe).

Use four shadows to simulate a stroked text:

_x000D_
_x000D_
.strokeme {_x000D_
  color: white;_x000D_
  text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;_x000D_
}
_x000D_
<div class="strokeme">_x000D_
  This text should have a stroke in some browsers_x000D_
</div>
_x000D_
_x000D_
_x000D_

I have made a demo for you here

And a hovered example is available here


As Jason C has mentioned in the comments, the text-shadow CSS property is now supported by all major browsers, with the exception of Opera Mini. Where this solution will work for backwards compatibility (not really an issue regarding browsers that auto-update) I believe the text-stroke CSS should be used.

How can I check if an argument is defined when starting/calling a batch file?

A more-advanced example:

? unlimited arguments.

? exist on file system (either file or directory?) or a generic string.

? specify if is a file

? specify is a directory

? no extensions, would work in legacy scripts!

? minimal code ?

@echo off

:loop
      ::-------------------------- has argument ?
      if ["%~1"]==[""] (
        echo done.
        goto end
      )
      ::-------------------------- argument exist ?
      if not exist %~s1 (
        echo not exist
      ) else (
        echo exist
        if exist %~s1\NUL (
          echo is a directory
        ) else (
          echo is a file
        )
      )
      ::--------------------------
      shift
      goto loop
      
      
:end

pause

? other stuff..?

¦ in %~1 - the ~ removes any wrapping " or '.

¦ in %~s1 - the s makes the path be DOS 8.3 naming, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "s.

¦ the ["%~1"]==[""] "can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1 (just without the " wrapping, if any..)

if there were no arguments of if we've used shift and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""].

¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)

¦ execution examples

save it as identifier.cmd

it can identify an unlimited arguments (normally you are limited to %1-%9), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).


this allows you to run the following commands:

?identifier.cmd c:\windows and to get

exist
is a directory
done

?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE" and to get

exist
is a file
done

? and multiple arguments (of course this is the whole-deal..)

identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world

and to get

exist
is a directory
exist
is a file
exist
is a file
not exist
done.

naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)

Hope it helps anyone :)

published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory

and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax

How do I use Spring Boot to serve static content located in Dropbox folder?

You can add your own static resource handler (it overwrites the default), e.g.

@Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("file:/path/to/my/dropbox/");
    }
}

There is some documentation about this in Spring Boot, but it's really just a vanilla Spring MVC feature.

Also since spring boot 1.2 (I think) you can simply set spring.resources.staticLocations.

How to get the top 10 values in postgresql?

Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided. Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains 10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT

Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column is technically in the top 10.

select
  *
from
  (select
     *,
     rank() over (order by some_value_column desc) as my_rank
  from mytable) subquery
where my_rank <= 10

psql: FATAL: role "postgres" does not exist

For me, this code worked:

/Applications/Postgres.app/Contents/Versions/9.4/bin/createuser -s postgres

it came from here: http://talk.growstuff.org/t/fatal-role-postgres-does-not-exist/216/4

How to remove folders with a certain name

This also works - it will remove all the folders called "a" and their contents:

rm -rf `find -type d -name a`

Embed YouTube Video with No Ads

Whether ads are shown on a video is up to the content owner of that video. It's not something that the embedder can control.

If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.

(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)

setTimeout or setInterval?

When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.

- E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
1) Browser run doStuff() which takes 1.5 sec. to be executed;
2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
As the result- the browser is stuck.

To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.

How do I create an array of strings in C?

I was missing somehow more dynamic array of strings, where amount of strings could be varied depending on run-time selection, but otherwise strings should be fixed.

I've ended up of coding code snippet like this:

#define INIT_STRING_ARRAY(...)          \
    {                                   \
        char* args[] = __VA_ARGS__;     \
        ev = args;                      \
        count = _countof(args);         \
    }

void InitEnumIfAny(String& key, CMFCPropertyGridProperty* item)
{
    USES_CONVERSION;
    char** ev = nullptr;
    int count = 0;

    if( key.Compare("horizontal_alignment") )
        INIT_STRING_ARRAY( { "top", "bottom" } )

    if (key.Compare("boolean"))
        INIT_STRING_ARRAY( { "yes", "no" } )

    if( ev == nullptr )
        return;

    for( int i = 0; i < count; i++)
        item->AddOption(A2T(ev[i]));

    item->AllowEdit(FALSE);
}

char** ev picks up pointer to array strings, and count picks up amount of strings using _countof function. (Similar to sizeof(arr) / sizeof(arr[0])).

And there is extra Ansi to unicode conversion using A2T macro, but that might be optional for your case.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

Since ng-show is an angular attribute i think, we don't need to put the evaluation flower brackets ({{}})..

For attributes like class we need to encapsulate the variables with evaluation flower brackets ({{}}).

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

Simple one-line code to save FULL size profile image on your server.

<?php

copy("https://graph.facebook.com/FACEBOOKID/picture?width=9999&height=9999", "picture.jpg");

?>

This will only work if openssl is enabled in php.ini.

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

  1. Under Window Administrative Tools, run ODBC Data Sources (32-bit).

  2. Under the Drivers tab, check you have the Microsoft Excel Driver (*.xls, *.xlsx etc...) - the file name is ACEODBC.DLL

  3. If this is missing, you will need to install the Microsoft Access Database Engine 2016 Redistributable.

You'll find the installer here https://www.microsoft.com/en-us/download/details.aspx?id=54920

  1. Your connection should be:
Set objConn1 = Server.CreateObject("ADODB.Connection") 
objConn1.Provider = "Microsoft.ACE.OLEDB.12.0"   
objConn1.ConnectionString = "Data Source=" & pPath & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1""" 

Convert.ToDateTime: how to set format

How about this:

    string test = "01-12-12";
    try{
         DateTime dateTime = DateTime.Parse(test);
         test = dateTime.ToString("dd/yyyy");
    }
    catch (FormatException exc)
    {
        MessageBox.Show(exc.Message);
    }

Where test will be equal to "12/2012"

Hope it helps!

Please read HERE.

Reading images in python

For the better answer, you can use these lines of code. Here is the example maybe help you :

image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()

In imread() you can pass the directory .so you can also use str() and + to combine dynamic directories and fixed directory like this:

path = '/home/pictures/'
for i in range(2) :
    image = cv2.imread(str(path)+'1.jpg')
    plt.imshow(image)
    plt.show()

Both are the same.

Load local JSON file into variable

There are two possible problems:

  1. AJAX is asynchronous, so json will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json to some value but at that time, nobody cares anymore.

    I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:

    console.log(['json', json]);
    
  2. The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Another solution I found to work is to set a mousewheel handler on the inside container and make sure it doesn't propagate by setting its last parameter to false and stopping the event bubble.

document.getElementById('content').addEventListener('mousewheel',function(evt){evt.cancelBubble=true;   if (evt.stopPropagation) evt.stopPropagation},false);

Scroll works fine in the inner container, but the event doesn't propagate to the body and so it does not scroll. This is in addition to setting the body properties overflow:hidden and height:100%.

Create pandas Dataframe by appending one row at a time

This is not an answer to the OP question but a toy example to illustrate the answer of @ShikharDua above which I found very useful.

While this fragment is trivial, in the actual data I had 1,000s of rows, and many columns, and I wished to be able to group by different columns and then perform the stats below for more than one taget column. So having a reliable method for building the data frame one row at a time was a great convenience. Thank you @ShikharDua !

import pandas as pd 

BaseData = pd.DataFrame({ 'Customer' : ['Acme','Mega','Acme','Acme','Mega','Acme'],
                          'Territory'  : ['West','East','South','West','East','South'],
                          'Product'  : ['Econ','Luxe','Econ','Std','Std','Econ']})
BaseData

columns = ['Customer','Num Unique Products', 'List Unique Products']

rows_list=[]
for name, group in BaseData.groupby('Customer'):
    RecordtoAdd={} #initialise an empty dict 
    RecordtoAdd.update({'Customer' : name}) #
    RecordtoAdd.update({'Num Unique Products' : len(pd.unique(group['Product']))})      
    RecordtoAdd.update({'List Unique Products' : pd.unique(group['Product'])})                   

    rows_list.append(RecordtoAdd)

AnalysedData = pd.DataFrame(rows_list)

print('Base Data : \n',BaseData,'\n\n Analysed Data : \n',AnalysedData)

Using HTML and Local Images Within UIWebView

My complex solution (or tutorial) for rss-feed (get in RSSItems) works only on device:

#define CACHE_DIR       [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

for (RSSItem *item in _dataSource) {

    url = [NSURL URLWithString:[item link]];
    request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                               @autoreleasepool {

                                   if (!error) {

                                       NSString *html = [[NSString alloc] initWithData:data
                                                                              encoding:NSWindowsCP1251StringEncoding];

                                       {
                                           NSError *error = nil;

                                           HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];

                                           if (error) {
                                               NSLog(@"Error: %@", error);
                                               return;
                                           }

                                           HTMLNode *bodyNode = [parser body];

                                           NSArray *spanNodes = [bodyNode findChildTags:@"div"];

                                           for (HTMLNode *spanNode in spanNodes) {
                                               if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"page"]) {

                                                   NSString *absStr = [[response URL] absoluteString];
                                                   for (RSSItem *anItem in _dataSource)
                                                       if ([absStr isEqualToString:[anItem link]]){

                                                           NSArray *spanNodes = [bodyNode findChildTags:@"img"];
                                                           for (HTMLNode *spanNode in spanNodes){
                                                               NSString *imgUrl = [spanNode getAttributeNamed:@"src"];
                                                               if (imgUrl){
                                                                   [anItem setImage:imgUrl];
                                                                   break;
                                                               }
                                                           }

                                                           [anItem setHtml:[spanNode rawContents]];
                                                           [self subProcessRSSItem:anItem];
                                                       }
                                               }
                                           }

                                           [parser release];
                                       }

                                       if (error) {
                                           NSLog(@"Error: %@", error);
                                           return;
                                       }

                                       [[NSNotificationCenter defaultCenter] postNotificationName:notification_updateDatasource
                                                                                           object:self
                                                                                         userInfo:nil];

                                   }else
                                       NSLog(@"Error",[error userInfo]);
                               }
                           }];

and

- (void)subProcessRSSItem:(RSSItem*)item{

NSString *html = [item html];
if (html) {

    html = [html stringByReplacingOccurrencesOfString:@"<div class=\"clear\"></div>"
                                           withString:@""];

    html = [html stringByReplacingOccurrencesOfString:@"<p class=\"link\">"
                                           withString:@""];

    html = [html stringByReplacingOccurrencesOfString:@"<div class=\"page\">"
                                           withString:@""];

    html = [html stringByReplacingOccurrencesOfString:@"</div>"
                                           withString:@""];

    NSArray *array1 = [html componentsSeparatedByString:@"<a"];
    if ([array1 count]==2) {
        NSArray *array2 = [html componentsSeparatedByString:@"a>"];

        html = [[array1 objectAtIndex:0] stringByAppendingString:[array2 objectAtIndex:1]];
    }

    NSURL *url;
    NSString *fileName;
    NSString *filePath;
    BOOL success;
    if ([item image]) {

        url = [NSURL URLWithString:
                      [hostString stringByAppendingString:[item image]]];
        NSData *imageData = [NSData dataWithContentsOfURL:url];

        fileName = [[[url relativePath] componentsSeparatedByString:@"/"] lastObject];

        filePath = [NSString stringWithFormat:@"%@/%@",
                              CACHE_DIR,
                              fileName];

        //save image locally
        success = [[NSFileManager defaultManager] createFileAtPath:filePath
                                                               contents:imageData
                                                             attributes:nil];

        //replace links
        html = [html stringByReplacingOccurrencesOfString:[item image]
                                               withString:filePath];

        [item setImage:fileName];

        //????????? ?????????? ??????????, ??????? ???????? ??????????? ??????
        [[NSNotificationCenter defaultCenter] postNotificationName:notification_updateRow
                                                            object:self
                                                          userInfo:[NSDictionary dictionaryWithObject:@([_dataSource indexOfObject:item])
                                                                                               forKey:@"row"]];
    }

    //finalize html
    html = [NSString stringWithFormat:@"<html><body>%@</body></html>",html];

    fileName = [[[item link] componentsSeparatedByString:@"/"] lastObject];
    filePath = [NSString stringWithFormat:@"%@/%@",
                CACHE_DIR,
                fileName];
    success = [[NSFileManager defaultManager] createFileAtPath:filePath
                                                      contents:[html dataUsingEncoding:NSUTF8StringEncoding]
                                                    attributes:nil];

    [item setHtml:
     (success)?filePath:nil];//for direct download in other case
}

}

on View controller

- (void)viewDidAppear:(BOOL)animated{

RSSItem *item = [[DataSingleton sharedSingleton] selectedRSSItem];

NSString* htmlString = [NSString stringWithContentsOfFile:[item html]
                                                 encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL URLWithString:CACHE_DIR];

[_webView loadHTMLString:htmlString
                 baseURL:baseURL];

}

rss item class

#import <Foundation/Foundation.h>

@interface RSSItem : NSObject

@property(nonatomic,retain) NSString *title;
@property(nonatomic,retain) NSString *link;
@property(nonatomic,retain) NSString *guid;
@property(nonatomic,retain) NSString *category;
@property(nonatomic,retain) NSString *description;
@property(nonatomic,retain) NSString *pubDate;
@property(nonatomic,retain) NSString *html;
@property(nonatomic,retain) NSString *image;
@end

part of any html with image

<html><body>
<h2>blah-blahTC One Tab 7</h2>
<p>blah-blah ??? One.</p>
<p><img width="600" height="412" alt="" src="/Users/wins/Library/Application Support/iPhone Simulator/5.0/Applications/2EAD8889-6482-48D4-80A7-9CCFD567123B/Library/Caches/htc-one-tab-7-concept-1(1).jpg"><br><br>
blah-blah (Hasan Kaymak) blah-blah HTC One Tab 7, blah-blah HTC One. <br><br>
blah-blah
 microSD.<br><br>
blah-blah Wi-Fi to 4G LTE.</p>
</p>
</body></html>

image saved for name htc-one-tab-7-concept-1(1).jpg

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Use Set in Python

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

What are my options for storing data when using React Native? (iOS and Android)

you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.

import SyncStorage from 'sync-storage';

SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

Best way to encode text data for XML

Microsoft's AntiXss library AntiXssEncoder Class in System.Web.dll has methods for this:

AntiXss.XmlEncode(string s)
AntiXss.XmlAttributeEncode(string s)

it has HTML as well:

AntiXss.HtmlEncode(string s)
AntiXss.HtmlAttributeEncode(string s)

Getting only response header from HTTP POST using curl

The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:

curl -s -I -X POST http://www.google.com

An -I by itself performs a HEAD request which can be overridden by -X POST to perform a POST (or any other) request and still only get the header data.

What is the best method of handling currency/money?

Common practice for handling currency is to use decimal type. Here is a simple example from "Agile Web Development with Rails"

add_column :products, :price, :decimal, :precision => 8, :scale => 2 

This will allow you to handle prices from -999,999.99 to 999,999.99
You may also want to include a validation in your items like

def validate 
  errors.add(:price, "should be at least 0.01") if price.nil? || price < 0.01 
end 

to sanity-check your values.

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

Determine if string is in list in JavaScript

A simplified version of SLaks' answer also works:

if ('abcdefghij'.indexOf(str) >= 0) {
    // Do something
}

....since strings are sort of arrays themselves. :)

If needed, implement the indexof function for Internet Explorer as described before me.

How do I get a value of datetime.today() in Python that is "timezone aware"?

In Python 3.2+: datetime.timezone.utc:

The standard library makes it much easier to specify UTC as the time zone:

>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)

You can also get a datetime that includes the local time offset using astimezone:

>>> datetime.datetime.now(datetime.timezone.utc).astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))

(In Python 3.6+, you can shorten the last line to: datetime.datetime.now().astimezone())

If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs' answer.

In Python 3.9+: zoneinfo to use the IANA time zone database:

In Python 3.9, you can specify particular time zones using the standard library, using zoneinfo, like this:

>>> from zoneinfo import ZoneInfo
>>> datetime.datetime.now(ZoneInfo("America/Los_Angeles"))
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))

zoneinfo gets its database of time zones from the operating system, or from the first-party PyPI package tzdata if available.

Java best way for string find and replace?

Another option:

"My name is Milan, people know me as Milan Vasic"
    .replaceAll("Milan Vasic|Milan", "Milan Vasic"))

How do you declare string constants in C?

The main disadvantage of the #define method is that the string is duplicated each time it is used, so you can end up with lots of copies of it in the executable, making it bigger.

How to resolve symbolic links in a shell script

readlink -e [filepath]

seems to be exactly what you're asking for - it accepts an arbirary path, resolves all symlinks, and returns the "real" path - and it's "standard *nix" that likely all systems already have

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

All those answers didnt help me, BUT I found another solution.

I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.

I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:

@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,

I simply removed orphanRemoval and the update worked.

ASP.NET Core 1.0 on IIS error 502.5

Worked for me after changing the publishing configuration.

enter image description here

How to remove new line characters from data rows in mysql?

Playing with above answers, this one works for me

REPLACE(REPLACE(column_name , '\n', ''), '\r', '')

Correct Semantic tag for copyright info - html5

In a link, if you put rel=license it: Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Source: http://www.w3.org/wiki/HTML/Elements/link

So, for example, <a rel="license" href="https://creativecommons.org/licenses/by/4.0/">Copyrighted but you can use what's here as long as you credit me</a> gives a human something to read and lets computers know that the rest of the page is licensed under the CC BY 4.0 license.

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:

=SUBTOTAL(9,B1:B20)

The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.

=SUBTOTAL(109,B1:B20)

The function number 109 is for the SUM function as well, but hidden rows are ignored.

Meaning of - <?xml version="1.0" encoding="utf-8"?>

The XML declaration in the document map consists of the following:

The version number, ?xml version="1.0"?. 

This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.

The encoding declaration,

encoding="UTF-8"?

This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

add the artifact from maven.

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
 </dependency>

Access to file download dialog in Firefox

I have a solution for this issue, check the code:

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

WebDriver driver = new FirefoxDriver(firefoxProfile);//new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);

driver.navigate().to("http://www.myfile.com/hey.csv");

Confirm deletion in modal / dialog using Twitter Bootstrap?

POST Recipe with navigation to target page and reusable Blade file

dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.

Using Blade I created the file resources/views/includes/confirmation_modal.blade.php:

<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>{{ $headerText }}</h4>
            </div>
            <div class="modal-body">
                {{ $bodyText }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <form action="" method="POST" style="display:inline">
                    {{ method_field($verb) }}
                    {{ csrf_field() }}
                    <input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $('#confirmation-modal').on('show.bs.modal', function(e) {
        href = $(e.relatedTarget).data('href');

        // change href of button to corresponding target
        $(this).find('form').attr('action', href);
    });
</script>

Now, using it is straight-forward:

<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>

Not much changed here and the modal can be included like this:

@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])

Just by putting the verb in there, it uses it. This way, CSRF is also utilized.

Helped me, maybe it helps someone else.

CSS Animation onClick

_x000D_
_x000D_
var  abox = document.getElementsByClassName("box")[0];_x000D_
function allmove(){_x000D_
        abox.classList.remove("move-ltr");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move");_x000D_
}_x000D_
function ltr(){_x000D_
        abox.classList.remove("move");_x000D_
        abox.classList.remove("move-ttb");_x000D_
       abox.classList.toggle("move-ltr");_x000D_
}_x000D_
function ttb(){_x000D_
       abox.classList.remove("move-ltr");_x000D_
       abox.classList.remove("move");_x000D_
       abox.classList.toggle("move-ttb");_x000D_
}
_x000D_
.box {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: red;_x000D_
  position: relative;_x000D_
}_x000D_
.move{_x000D_
  -webkit-animation: moveall 5s;_x000D_
  animation: moveall 5s;_x000D_
}_x000D_
.move-ltr{_x000D_
   -webkit-animation: moveltr 5s;_x000D_
  animation: moveltr 5s;_x000D_
}_x000D_
.move-ttb{_x000D_
    -webkit-animation: movettb 5s;_x000D_
  animation: movettb 5s;_x000D_
}_x000D_
@keyframes moveall {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  25%  {left: 200px; top: 0px;}_x000D_
  50%  {left: 200px; top: 200px;}_x000D_
  75%  {left: 0px; top: 200px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes moveltr {_x000D_
  0%   { left: 0px; top: 0px;}_x000D_
  50%  {left: 200px; top: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}_x000D_
@keyframes movettb {_x000D_
  0%   {left: 0px; top: 0px;}_x000D_
  50%  {top: 200px;left: 0px;}_x000D_
  100% {left: 0px; top: 0px;}_x000D_
}
_x000D_
<div class="box"></div>_x000D_
<button onclick="allmove()">click</button>_x000D_
<button onclick="ltr()">click</button>_x000D_
<button onclick="ttb()">click</button>
_x000D_
_x000D_
_x000D_

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

Start your XAMPP server by using:

  • {XAMPP}\xampp-control.exe
  • {XAMPP}\apache_start.bat

Then you have to use the URI http://localhost/index.html because htdocs is the document root of the Apache server.

If you're getting redirected to http://localhost/xampp/*, then index.php located in the htdocs folder is the problem because index.php files have a higher priority than index.html files. You could temporarily rename index.php.

How to check whether Kafka Server is running?

I used the AdminClient api.

Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try (AdminClient client = KafkaAdminClient.create(properties))
{
    ListTopicsResult topics = client.listTopics();
    Set<String> names = topics.names().get();
    if (names.isEmpty())
    {
        // case: if no topic found.
    }
    return true;
}
catch (InterruptedException | ExecutionException e)
{
    // Kafka is not available
}

How to Use slideDown (or show) function on a table row?

I'm a bit behind the times on answering this, but I found a way to do it :)

function eventinfo(id) {
    tr = document.getElementById("ei"+id);
    div = document.getElementById("d"+id);
    if (tr.style.display == "none") {
        tr.style.display="table-row";
        $(div).slideDown('fast');
    } else {
        $(div).slideUp('fast');
        setTimeout(function(){tr.style.display="none";}, 200);
    }
}

I just put a div element inside the table data tags. when it is set visible, as the div expands, the whole row comes down. then tell it to fade back up (then timeout so you see the effect) before hiding the table row again :)

Hope this helps someone!

Open files in 'rt' and 'wt' modes

The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.

Other than U, those mode flags come directly from the standard C library's fopen() function, a fact that is documented in the sixth paragraph of the python2 documentation for open().

As far as I know, t is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

TempData keep() vs peek()

don't they both keep a value for another request?

Yes they do, but when the first one is void, the second one returns and object:

public void Keep(string key)
{
    _retainedKeys.Add(key); // just adds the key to the collection for retention
}

public object Peek(string key)
{
    object value;
    _data.TryGetValue(key, out value);
    return value; // returns an object without marking it for deletion
}

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

How can I count text lines inside an DOM element? Can I?

Try this solution:

function calculateLineCount(element) {
  var lineHeightBefore = element.css("line-height"),
      boxSizing        = element.css("box-sizing"),
      height,
      lineCount;

  // Force the line height to a known value
  element.css("line-height", "1px");

  // Take a snapshot of the height
  height = parseFloat(element.css("height"));

  // Reset the line height
  element.css("line-height", lineHeightBefore);

  if (boxSizing == "border-box") {
    // With "border-box", padding cuts into the content, so we have to subtract
    // it out
    var paddingTop    = parseFloat(element.css("padding-top")),
        paddingBottom = parseFloat(element.css("padding-bottom"));

    height -= (paddingTop + paddingBottom);
  }

  // The height is the line count
  lineCount = height;

  return lineCount;
}

You can see it in action here: https://jsfiddle.net/u0r6avnt/

Try resizing the panels on the page (to make the right side of the page wider or shorter) and then run it again to see that it can reliably tell how many lines there are.

This problem is harder than it looks, but most of the difficulty comes from two sources:

  1. Text rendering is too low-level in browsers to be directly queried from JavaScript. Even the CSS ::first-line pseudo-selector doesn't behave quite like other selectors do (you can't invert it, for example, to apply styling to all but the first line).

  2. Context plays a big part in how you calculate the number of lines. For example, if line-height was not explicitly set in the hierarchy of the target element, you might get "normal" back as a line height. In addition, the element might be using box-sizing: border-box and therefore be subject to padding.

My approach minimizes #2 by taking control of the line-height directly and factoring in the box sizing method, leading to a more deterministic result.

Compare two List<T> objects for equality, ignoring order

As written, this question is ambigous. The statement:

... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.

does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.

If you want to ensure to collections have exactly the same set of members regardless of order, you can use:

// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();

If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:

// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();

Using the set operations (Intersect, Union, Except) is more efficient than using methods like Contains. In my opinion, it also better expresses the expectations of your query.

EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:

var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };

// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any(); 

Oracle SQL Query for listing all Schemas in a DB

Most likely, you want

SELECT username
  FROM dba_users

That will show you all the users in the system (and thus all the potential schemas). If your definition of "schema" allows for a schema to be empty, that's what you want. However, there can be a semantic distinction where people only want to call something a schema if it actually owns at least one object so that the hundreds of user accounts that will never own any objects are excluded. In that case

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )

Assuming that whoever created the schemas was sensible about assigning default tablespaces and assuming that you are not interested in schemas that Oracle has delivered, you can filter out those schemas by adding predicates on the default_tablespace, i.e.

SELECT username
  FROM dba_users
 WHERE default_tablespace not in ('SYSTEM','SYSAUX')

or

SELECT username
  FROM dba_users u
 WHERE EXISTS (
    SELECT 1
      FROM dba_objects o
     WHERE o.owner = u.username )
   AND default_tablespace not in ('SYSTEM','SYSAUX')

It is not terribly uncommon to come across a system where someone has incorrectly given a non-system user a default_tablespace of SYSTEM, though, so be certain that the assumptions hold before trying to filter out the Oracle-delivered schemas this way.

When to use setAttribute vs .attribute= in JavaScript?

You should always use the direct .attribute form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.

Use getAttribute/setAttribute when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.

Page redirect after certain time PHP

You can use this javascript code to redirect after a specific time. Hope it will work.

setRedirectTime(function () 
{
   window.location.href= 'https://www.google.com'; // the redirect URL will be here

},10000); // 10 seconds

How do I resize an image using PIL and maintain its aspect ratio?

This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change "basewidth" to any other number to change the default width of your images.

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('somepic.jpg')

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

Creating a very simple linked list

Add a Node class.
Then add a LinkedList class to implement the linked list
Add a test class to execute the linked list

namespace LinkedListProject
{
    public class Node
    {
        public Node next;
        public object data;
    }

    public class MyLinkedList
    {
        Node head;
        public Node AddNodes(Object data)
        {
            Node node = new Node();

            if (node.next == null)
            {
                node.data = data;
                node.next = head;
                head = node;
            }
            else
            {
                while (node.next != null)
                    node = node.next;

                node.data = data;
                node.next = null;

            }
            return node;
        }

        public void printnodes()
        {
            Node current = head;
            while (current.next != null)
            {
                Console.WriteLine(current.data);
                current = current.next;
            }
            Console.WriteLine(current.data);
        }
    }


    [TestClass]
    public class LinkedListExample
    {
        MyLinkedList linkedlist = new MyLinkedList();
        [TestMethod]
        public void linkedlisttest()
        {
            linkedlist.AddNodes("hello");
            linkedlist.AddNodes("world");
            linkedlist.AddNodes("now");
            linkedlist.printnodes();
        }
    }
}

How to convert characters to HTML entities using plain JavaScript

All the other solutions suggested here, as well as most other JavaScript libraries that do HTML entity encoding/decoding, make several mistakes:

For a robust solution that avoids all these issues, use a library I wrote called he for this. From its README:

he (for “HTML entities”) is a robust HTML entity encoder/decoder written in JavaScript. It supports all standardized named character references as per HTML, handles ambiguous ampersands and other edge cases just like a browser would, has an extensive test suite, and — contrary to many other JavaScript solutions — he handles astral Unicode symbols just fine. An online demo is available.

How to pass arguments to Shell Script through docker run

With Docker, the proper way to pass this sort of information is through environment variables.

So with the same Dockerfile, change the script to

#!/bin/bash
echo $FOO

After building, use the following docker command:

docker run -e FOO="hello world!" test

How do I remove a submodule?

In latest git just 4 operation is needed to remove the git submodule.

  • Remove corresponding entry in .gitmodules
  • Stage changes git add .gitmodules
  • Remove the submodule directory git rm --cached <path_to_submodule>
  • Commit it git commit -m "Removed submodule xxx"

How do I start a program with arguments when debugging?

For Visual Studio Code:

  • Open launch.json file
  • Add args to your configuration:

"args": ["some argument", "another one"],

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

When should I write the keyword 'inline' for a function/method?

  • When will the the compiler not know when to make a function/method 'inline'?

This depends on the compiler used. Do not blindly trust that nowadays compilers know better then humans how to inline and you should never use it for performance reasons, because it's linkage directive rather than optimization hint. While I agree that ideologically are these arguments correct encountering reality might be a different thing.

After reading multiple threads around I tried out of curiosity the effects of inline on the code I'm just working and the results were that I got measurable speedup for GCC and no speed up for Intel compiler.

(More detail: math simulations with few critical functions defined outside class, GCC 4.6.3 (g++ -O3), ICC 13.1.0 (icpc -O3); adding inline to critical points caused +6% speedup with GCC code).

So if you qualify GCC 4.6 as a modern compiler the result is that inline directive still matters if you write CPU intensive tasks and know where exactly is the bottleneck.

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

SOLVED

  1. Just run CMD as an administrator.
  2. Make sure your using the correct truststore password

Convert Pandas DataFrame to JSON format

convert data-frame to list of dictionary

list_dict = []

for index, row in list(df.iterrows()):
    list_dict.append(dict(row))

save file

with open("output.json", mode) as f:
    f.write("\n".join(str(item) for item in list_dict))

Find the host name and port using PSQL commands

From the terminal you can simply do a "postgres list clusters":

pg_lsclusters

It will return Postgres version number, cluster names, ports, status, owner, and the location of your data directories and log file.