Programs & Examples On #Apache config

Apache configuration is text based configuration file (or set of files) which are used to configure apache httpd web server

How to change the default encoding to UTF-8 for Apache?

Just a hint if you have long filenames in utf-8: by default they will be shortened to 20 bytes, so it may happen that the last character might be "cut in half" and therefore unrecognized properly. Then you may want to set the following:

IndexOptions Charset=UTF-8 NameWidth=*

NameWidth setting will prevent shortening your file names, making them properly displayed and readable.

As other users already mentioned, this should be added either in httpd.conf or apache2.conf (if you do have admin rights) or in .htaccess (if you don't).

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

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

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

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

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

Requirements:

.htaccess not working apache

In WampServer Open WampServer Tray icon ----> Apache ---> Apache Modules --->rewrite_module

Configure apache to listen on port other than 80

This is working for me on Centos

First: in file /etc/httpd/conf/httpd.conf

add

Listen 8079 

after

Listen 80

This till your server to listen to the port 8079

Second: go to your virtual host for ex. /etc/httpd/conf.d/vhost.conf

and add this code below

<VirtualHost *:8079>
   DocumentRoot /var/www/html/api_folder
   ServerName example.com
   ServerAlias www.example.com
   ServerAdmin [email protected]
   ErrorLog logs/www.example.com-error_log
   CustomLog logs/www.example.com-access_log common
</VirtualHost>

This mean when you go to your www.example.com:8079 redirect to

/var/www/html/api_folder

But you need first to restart the service

sudo service httpd restart

Best way to log POST data in Apache?

You can use [ModSecurity][1] to view POST data.

Install on Debian/Ubuntu:

$ sudo apt install libapache2-mod-security2

Use the recommended configuration file:

$ sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Reload Apache:

$ sudo service apache2 reload

You will now find your data logged under /var/log/apache2/modsec_audit.log

$ tail -f /var/log/apache2/modsec_audit.log
--2222229-A--
[23/Nov/2017:11:36:35 +0000] 
--2222229-B--
POST / HTTP/1.1
Content-Type: application/json
User-Agent: curl
Host: example.com

--2222229-C--
{"test":"modsecurity"}

index.php not loading by default

Try creating a .htaccess file with the following

DirectoryIndex index.php

Edit: Actually, isn't there a 'php-apache' package or something that you're supposed to install with both of them?

How to make sure docker's time syncs with that of the host?

Enabling Hyper-V in Windows Features solved the problem: Windows Features

How to sum array of numbers in Ruby?

Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):

require 'activesupport'
array.sum

Spring JPA selecting specific columns

You can apply the below code in your repository interface class.

entityname means your database table name like projects. And List means Project is Entity class in your Projects.

@Query(value="select p from #{#entityName} p where p.id=:projectId and p.projectName=:projectName")

List<Project> findAll(@Param("projectId") int projectId, @Param("projectName") String projectName);

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I hit this issue working with Server Sent Events. The problem was solved when I noticed that the domain name I used to initiate the connection included a trailing slash, e.g. https://foo.bar.bam/ failed with ERR_HTTP_PROTOCOL_ERROR while https://foo.bar.bam worked.

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

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

Node.js connect only works on localhost

I have a very simple solution for this problem: process.argv gives you a list of arguments passed to node app. So if you run:

node server.js 0.0.0.0

You'll get:

process.argv[0] //=> "node"
process.argv[1] //=> "server.js"
process.argv[2] //=> "0.0.0.0"

So you can use process.argv[2] to specify that as the IP address you want to listen to:

http.listen(3000, process.argv[2]);

Now, your app is listening to "all" IP addresses, for example http://192.168.1.4:3000/your_app.

I hope this will help someone!

Clearing an input text field in Angular2

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }

Remove last character of a StringBuilder?

Here is another solution:

for(String serverId : serverIds) {
   sb.append(",");
   sb.append(serverId); 
}

String resultingString = "";
if ( sb.length() > 1 ) {
    resultingString = sb.substring(1);
}

Maven Run Project

The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass and give its value as the class which contains your main method. For me it was DriverClass in mainpkg. Change it as per your project. enter image description here

Having done this navigate to the folder that contains your project's pom.xml and run this on the command prompt mvn exec:java. This should call the main method.

How to clear form after submit in Angular 2?

Below code works for me in Angular 4

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
 registerForm: FormGroup; 

 constructor(private formBuilder: FormBuilder) { }   

 ngOnInit() {
    this.registerForm = this.formBuilder.group({
      empname: [''],
      empemail: ['']
    });
 }

 onRegister(){
    //sending data to server using http request
    this.registerForm.reset()
 }

}

How do I completely rename an Xcode project (i.e. inclusive of folders)?

Adding to the accepted answer by Luke West. If you have any entitlements:

  1. Close Xcode
  2. Change the entitlements filename
  3. Go into Xcode, select the entitlements file should be highlighted red, in the File inspector select the Folder icon and select your renamed file.
  4. Go into Build Settings, and search "entitlements" and update the folder name and file name for the entitlement.
  5. Clean and rebuild

Apache and IIS side by side (both listening to port 80) on windows2003

You will need to use different IP addresses. The server, whether Apache or IIS, grabs the traffic based on the IP and Port, which ever they are bound to listen to. Once it starts listening, then it uses the headers, such as the server name to filter and determine what site is being accessed. You can't do it will simply changing the server name in the request

REST, HTTP DELETE and parameters

I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.

Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?

PHP Undefined Index

The checking of the presence of the member before assigning it is, in my opinion, quite ugly.

Kohana has a useful function to make selecting parameters simple.

You can make your own like so...

function arrayGet($array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

And then do something like...

$page = arrayGet($_GET, 'p', 1);

How to create a horizontal loading progress bar?

Progress Bar in Layout

<ProgressBar 
               android:id="@+id/download_progressbar"
               android:layout_width="200dp"
               android:layout_height="24dp"
               android:background="@drawable/download_progress_bg_track"
               android:progressDrawable="@drawable/download_progress_style"
               style="?android:attr/progressBarStyleHorizontal"
               android:indeterminate="false"
               android:indeterminateOnly="false" />

download_progress_style.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress">
    <scale 
      android:useIntrinsicSizeAsMinimum="true" 
      android:scaleWidth="100%" 
      android:drawable="@drawable/store_download_progress" />
</item>

Telegram Bot - how to get a group chat id?

I tested now 4h but it dont work 2021 with the group-chat-id. All the time the error {"ok":true,"result":[]}

But now i found a Solution:

1:) install the "Plus Messenger" (https://play.google.com/store/apps/details?id=org.telegram.plus)

2:) go in the Group => Tap now on the "Group-Name" in the Head => Double Tap now on the Headline from the Group. A Info is comming: ID123456789 is copy in the clipboard

3:) go in the Group an paste the clipboard text. It´s you Groud-ID

4:) looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!

btw, you see the user-id too, on your profil.

5:) Now go to the Webbrowser an send this line (Test Message):

https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test

Edit the API Token and the Group-ID!

How to align content of a div to the bottom

Here is another solution using flexbox but without using flex-end for bottom alignment. The idea is to set margin-bottom on h1 to auto to push the remaining content to the bottom:

_x000D_
_x000D_
#header {_x000D_
  height: 350px;_x000D_
  display:flex;_x000D_
  flex-direction:column;_x000D_
  border:1px solid;_x000D_
}_x000D_
_x000D_
#header h1 {_x000D_
 margin-bottom:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Header title</h1>_x000D_
  Header content (one or multiple lines) Header content (one or multiple lines)Header content (one or multiple lines) Header content (one or multiple lines)_x000D_
</div>
_x000D_
_x000D_
_x000D_

We can also do the same with margin-top:auto on the text but in this case we need to wrap it inside a div or span:

_x000D_
_x000D_
#header {_x000D_
  height: 350px;_x000D_
  display:flex;_x000D_
  flex-direction:column;_x000D_
  border:1px solid;_x000D_
}_x000D_
_x000D_
#header span {_x000D_
 margin-top:auto;_x000D_
}
_x000D_
<div id="header">_x000D_
  <h1>Header title</h1>_x000D_
  <span>Header content (one or multiple lines)</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ReactJS - How to use comments?

JavaScript comments in JSX get parsed as Text and show up in your app.

You can’t just use HTML comments inside of JSX because it treats them as DOM Nodes:

render() {
  return (
    <div>
      <!-- This doesn't work! -->
    </div>
  )
}

JSX comments for single line and multiline comments follows the convention

Single line comment:

{/* A JSX comment */}

Multiline comments:

{/* 
  Multi
  line
  comment
*/}  

Watermark / hint text / placeholder TextBox

<Window.Resources>

    <Style x:Key="TextBoxUserStyle" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
      <Setter Property="Foreground" Value="Black"/>
      <Setter Property="HorizontalAlignment" Value="Center"/>
      <Setter Property="VerticalContentAlignment" Value="Center"/>
      <Setter Property="Width" Value="225"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="FontSize" Value="12"/>
      <Setter Property="Padding" Value="1"/>
      <Setter Property="Margin" Value="5"/>
      <Setter Property="AllowDrop" Value="true"/>
      <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type TextBox}">
            <Border x:Name="OuterBorder" BorderBrush="#5AFFFFFF" BorderThickness="1,1,1,1" CornerRadius="4,4,4,4">
              <Border x:Name="InnerBorder" Background="#FFFFFFFF" BorderBrush="#33000000" BorderThickness="1,1,1,1" CornerRadius="3,3,3,3">
                <ScrollViewer SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="PART_ContentHost"/>
              </Border>
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

    <Style x:Key="PasswordBoxVistaStyle" BasedOn="{x:Null}" TargetType="{x:Type PasswordBox}">
      <Setter Property="Foreground" Value="Black"/>
      <Setter Property="HorizontalAlignment" Value="Center"/>
      <Setter Property="VerticalContentAlignment" Value="Center"/>
      <Setter Property="Width" Value="225"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="FontSize" Value="12"/>
      <Setter Property="Padding" Value="1"/>
      <Setter Property="Margin" Value="5"/>
      <Setter Property="AllowDrop" Value="true"/>
      <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type PasswordBox}">
            <Border x:Name="OuterBorder" BorderBrush="#5AFFFFFF" BorderThickness="1,1,1,1" CornerRadius="4,4,4,4">
              <Border x:Name="InnerBorder" Background="#FFFFFFFF" BorderBrush="#33000000" BorderThickness="1,1,1,1" CornerRadius="3,3,3,3">
                <Grid>
                  <Label x:Name="lblPwd" Content="Password" FontSize="11" VerticalAlignment="Center" Margin="2,0,0,0" FontFamily="Verdana" Foreground="#828385" Padding="0"/>
                  <ScrollViewer SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="PART_ContentHost"/>
                </Grid>
              </Border>
            </Border>
            <ControlTemplate.Triggers>
              <Trigger Property="IsFocused" Value="True">
                <Setter Property="Visibility" TargetName="lblPwd" Value="Hidden"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>


        <PasswordBox Style="{StaticResource PasswordBoxVistaStyle}" Margin="169,143,22,0" Name="txtPassword" FontSize="14" TabIndex="2" Height="31" VerticalAlignment="Top" />

This can help check it with your code.When applied to password box,it will show Password,which will disappear when usertypes.

Windows batch: formatted date into variable

If you have Python installed, you can do

python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"

You can easily adapt the format string to your needs.

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

Comment out HTML and PHP together

I agree that Pascal's solution is the way to go, but for those saying that it adds an extra task to remove the comments, you can use the following comment style trick to simplify your life:

<?php /* ?>
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
<?php // */ ?>

In order to stop the code block being commented out, simply change the opening comment to:

<?php //* ?>

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set AUTO_INCREMENT to PRIMARY KEY

Is it possible to get a history of queries made in postgres

If The question is the see the history of queries executed in the Command line. Answer is

As per Postgresql 9.3, Try \? in your command line, you will find all possible commands, in that search for history,

  \s [FILE]              display history or save it to file

in your command line, try \s. This will list the history of queries, you have executed in the current session. you can also save to the file, as shown below.

hms=# \s /tmp/save_queries.sql
Wrote history to file ".//tmp/save_queries.sql".
hms=# 

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

Insert Picture into SQL Server 2005 Image Field using only SQL

I achieved the goal where I have multiple images to insert in the DB as

INSERT INTO [dbo].[User]
           ([Name]
           ,[Image1]
           ,[Age]
           ,[Image2]
           ,[GroupId]
           ,[GroupName])
           VALUES
           ('Umar'
           , (SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
           ,26
           ,(SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
            ,'Group123'
           ,'GroupABC')

Minimal web server using netcat

Add -q 1 to the netcat command line:

while true; do 
  echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 -q 1
done

return SQL table as JSON in python

nobody seem to have offered the option to get the JSON directly from the Postgresql server, using the postgres JSON capability https://www.postgresql.org/docs/9.4/static/functions-json.html

No parsing, looping or any memory consumption on the python side, which you may really want to consider if you're dealing with 100,000's or millions of rows.

from django.db import connection

sql = 'SELECT to_json(result) FROM (SELECT * FROM TABLE table) result)'
with connection.cursor() as cursor:
  cursor.execute(sql)
  output = cursor.fetchall()

a table like:

id, value
----------
1     3
2     7

will return a Python JSON Object

[{"id": 1, "value": 3},{"id":2, "value": 7}]

Then use json.dumps to dump as a JSON string

Apply style to only first level of td tags

I think, It will work.

.Myclass tr td:first-child{ }

 or 

.Myclass td:first-child { }

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.

If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll (assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.

If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

Passing parameters to addTarget:action:forControlEvents

action:@selector(switchToNewsDetails:)

You do not pass parameters to switchToNewsDetails: method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:

  1. with no parameters

    action:@selector(switchToNewsDetails)
    
  2. with 1 parameter indicating the control that sends the message

    action:@selector(switchToNewsDetails:)
    
  3. With 2 parameters indicating the control that sends the message and the event that triggered the message:

    action:@selector(switchToNewsDetails:event:)
    

It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:

  1. set a tag property to each button equal to required index
  2. in switchToNewsDetails: method you can obtain that index and open appropriate deatails:

    - (void)switchToNewsDetails:(UIButton*)sender{
        [self openDetails:sender.tag];
        // Or place opening logic right here
    }
    

How to get all table names from a database?

In your example problem is passed table name pattern in getTables function of DatabaseMetaData.

Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.

DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()

From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.

public class DBUtility {
    private static final String[] TYPES = {"TABLE", "VIEW"};
    public static void getTableMetadata(Connection jdbcConnection, String tableNamePattern, String schema, String catalog, boolean isQuoted) throws HibernateException {
            try {
                DatabaseMetaData meta = jdbcConnection.getMetaData();
                ResultSet rs = null;
                try {
                    if ( (isQuoted && meta.storesMixedCaseQuotedIdentifiers())) {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    } else if ( (isQuoted && meta.storesUpperCaseQuotedIdentifiers())
                        || (!isQuoted && meta.storesUpperCaseIdentifiers() )) {
                        rs = meta.getTables(
                                StringHelper.toUpperCase(catalog),
                                StringHelper.toUpperCase(schema),
                                StringHelper.toUpperCase(tableNamePattern),
                                TYPES
                            );
                    }
                    else if ( (isQuoted && meta.storesLowerCaseQuotedIdentifiers())
                            || (!isQuoted && meta.storesLowerCaseIdentifiers() )) {
                        rs = meta.getTables( 
                                StringHelper.toLowerCase( catalog ),
                                StringHelper.toLowerCase(schema), 
                                StringHelper.toLowerCase(tableNamePattern), 
                                TYPES 
                            );
                    }
                    else {
                        rs = meta.getTables(catalog, schema, tableNamePattern, TYPES);
                    }

                    while ( rs.next() ) {
                        String tableName = rs.getString("TABLE_NAME");
                        System.out.println("table = " + tableName);
                    }



                }
                finally {
                    if (rs!=null) rs.close();
                }
            }
            catch (SQLException sqlException) {
                // TODO 
                sqlException.printStackTrace();
            }

    }

    public static void main(String[] args) {
        Connection jdbcConnection;
        try {
            jdbcConnection = DriverManager.getConnection("", "", "");
            getTableMetadata(jdbcConnection, "tbl%", null, null, false);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

how to check the jdk version used to compile a .class file

You can try jclasslib:

https://github.com/ingokegel/jclasslib

It's nice that it can associate itself with *.class extension.

Let JSON object accept bytes or let urlopen output strings

As of Python 3.6, you can use json.loads() to deserialize a bytesobject directly (the encoding must be UTF-8, UTF-16 or UTF-32). So, using only modules from the standard library, you can do:

import json
from urllib import request

response = request.urlopen(url).read()
data = json.loads(response)

Tar error: Unexpected EOF in archive

In my case, I had started untar before the uploading of the tar file was complete.

How to run Tensorflow on CPU

The environment variable solution doesn't work for me running tensorflow 2.3.1. I assume by the comments in the github thread that the below solution works for versions >=2.1.0.

From tensorflow github:

import tensorflow as tf

# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')

Make sure to do this right after the import with fresh tensorflow instance (if you're running jupyter notebook, restart the kernel).

And to check that you're indeed running on the CPU:

# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)

# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

Expected output:

2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)

What is the maximum length of a Push Notification alert text?

It should be 236 bytes. There is no restriction on the size of the alert text as far as I know, but only the total payload size. So considering if the payload is minimal and only contains the alert information, it should look like:

{"aps":{"alert":""}}

That takes up 20 characters (20 bytes), leaving 236 bytes to put inside the alert string. With ASCII that will be 236 characters, and could be lesser with UTF8 and UTF16.

How to avoid Number Format Exception in java?

one posibility: catch the exception and show an error message within the user frontend.

edit: add an listener to the field within the gui and check the user inputs there too, with this solution the exception case should be very rare...

ReactJS - Does render get called any time "setState" is called?

Another reason for "lost update" can be the next:

  • If the static getDerivedStateFromProps is defined then it is rerun in every update process according to official documentation https://reactjs.org/docs/react-component.html#updating.
  • so if that state value comes from props at the beginning it is overwrite in every update.

If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this

static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
   return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}

Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)

Full Screen DialogFragment in Android

Try to use setStyle() in onCreate and override onCreateDialog make dialog without title

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme);        
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        
    return dialog;
}

or just override onCreate() and setStyle fellow the code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme);        
}

Java 8 Lambda function that throws exception?

This is not specific to Java 8. You are trying to compile something equivalent to:

interface I {
    void m();
}
class C implements I {
    public void m() throws Exception {} //can't compile
}

Displaying a webcam feed using OpenCV and Python

If you only have one camera, or you don't care which camera is the correct one, then use "-1" as the index. Ie for your example capture = cv.CaptureFromCAM(-1).

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

Convert array of integers to comma-separated string

.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))

Show row number in row header of a DataGridView

You can also draw the string dynamically inside the RowPostPaint event:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

You could try git reset --hard HEAD to reset the repo to the expected default state.

Find the division remainder of a number

26 % 7 (you will get remainder)

26 / 7 (you will get divisor can be float value )

26 // 7 (you will get divisor only integer value) )

Convert RGBA PNG to RGB with PIL

import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3)) 
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]  
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

How to convert float value to integer in php?

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

How to write a basic swap function in Java

You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:

T t = p
p = q
q = t

where T is the type of p and q

However, swapping mutable objects may be possible by rewriting properties:

void swap(Point a, Point b) {
  int tx = a.x, ty = a.y;
  a.x = b.x; a.y = b.y;
  b.x = t.x; b.y = t.y;
}

How are "mvn clean package" and "mvn clean install" different?

Package & install are various phases in maven build lifecycle. package phase will execute all phases prior to that & it will stop with packaging the project as a jar. Similarly install phase will execute all prior phases & finally install the project locally for other dependent projects.

For understanding maven build lifecycle please go through the following link https://ayolajayamaha.blogspot.in/2014/05/difference-between-mvn-clean-install.html

Inserting Data into Hive Table

Use this -

create table dummy_table_name as select * from source_table_name;

This will create the new table with existing data available on source_table_name.

What is the worst programming language you ever worked with?

Oberon.

In our first year at university, everyone had to program in Oberon. I think the idea was to make sure nobody had a head start. The language was tied to the Oberon OS/GUI which was horrible! I'm not sure if anything changed, but that was definitely my worst programming experience ever.

PHP/MySQL: How to create a comment section in your website

This is my way i do comments (I think its secure):

<h1>Comment's:</h1>
<?php 
$i  = addslashes($_POST['a']);
$ip = addslashes($_POST['b']);
$a  = addslashes($_POST['c']);
$b  = addslashes($_POST['d']);
if(isset($i) & isset($ip) & isset($a) & isset($b))
{
    $r = mysql_query("SELECT COUNT(*) FROM $db.ban WHERE ip=$ip"); //Check if banned
    $r = mysql_fetch_array($r);
    if(!$r[0]) //Phew, not banned
    {
        if(mysql_query("INSERT INTO $db.com VALUES ($a, $b, $ip, $i)"))
        {
            ?>
            <script type="text/javascript">
                window.location="/index.php?id=".<?php echo $i; ?>;
            </script>
            <?php
        }
        else echo "Error, in mysql query";  
    }
    else echo "Error, You are banned.";
}
$x = mysql_query("SELECT * FROM $db.com WHERE i=$i");
while($r = mysql_fetch_object($x) echo '<div class="c">'.$r->a.'<p>'.$row->b.'</p> </div>';

?>  
<h1>Leave a comment, pl0x:</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="a" value="<?php $echo $_GET['id']; ?>" />
    <input type="hidden" name="b" value="<?php $echo $_SERVER['REMOTE_ADDR']; ?>" />
    <input type="text" name="c" value="Name"/></br>
    <textarea name="d">
    </textarea>
    <input type="submit" />
</form>

This does it all in one page (This is only the comments section, some configuration is needed)

PHP Configuration: It is not safe to rely on the system's timezone settings

Open your .htaccess file , add this line to the file, save, and try again :

php_value date.timezone "America/Sao_Paulo"

This works for me.

How can I quantify difference between two images?

I think you could simply compute the euclidean distance (i.e. sqrt(sum of squares of differences, pixel by pixel)) between the luminance of the two images, and consider them equal if this falls under some empirical threshold. And you would better do it wrapping a C function.

Move to another EditText when Soft Keyboard Next is clicked on Android

Use the following line

android:nextFocusDown="@+id/parentedit"

parentedit is the ID of the next EditText to be focused.

The above line will also need the following line.

android:inputType="text"

or

android:inputType="number"

Thanks for the suggestion @Alexei Khlebnikov.

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

There are 3 ways to solve this issue while development. Any one from below can solve this issue.
1) provide the changes in new migration sql file with incrementing version
2) change the schema name in db url we provide
datasource.flyway.url=jdbc:h2:file:~/cart3
datasource.flyway.url=jdbc:h2:file:~/cart4
3) delete the .mv and .trace files in users home directory
ex: cart3.mv and cart3.trace under c://users/username/

How do I use boolean variables in Perl?

I recommend use boolean;. You have to install the boolean module from cpan though.

How do I clear the dropdownlist values on button click event using jQuery?

A shorter alternative to the first solution given by Russ Cam would be:

$('#mySelect').val('');

This assumes you want to retain the list, but make it so that no option is selected.

If you wish to select a particular default value, just pass that value instead of an empty string.

$('#mySelect').val('someDefaultValue');

or to do it by the index of the option, you could do:

$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option

Select Last Row in the Table

You never mentioned whether you are using Eloquent, Laravel's default ORM or not. In case you are, let's say you want to get the latest entry of a User table, by created_at, you probably could do as follow:

User::orderBy('created_at', 'desc')->first();

First it orders users by created_at field, descendingly, and then it takes the first record of the result.

That will return you an instance of the User object, not a collection. Of course, to make use of this alternative, you got to have an User model, extending Eloquent class. This may sound a bit confusing, but it's really easy to get started and ORM can be really helpful.

For more information, check out the official documentation which is pretty rich and well detailed.

Iterate two Lists or Arrays with one ForEach statement in C#

I often need to execute an action on each pair in two collections. The Zip method is not useful in this case.

This extension method ForPair can be used:

public static void ForPair<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second,
    Action<TFirst, TSecond> action)
{
    using (var enumFirst = first.GetEnumerator())
    using (var enumSecond = second.GetEnumerator())
    {
        while (enumFirst.MoveNext() && enumSecond.MoveNext())
        {
            action(enumFirst.Current, enumSecond.Current);
        }
    }
}

So for example, you could write:

var people = new List<Person> { person1, person2 };
var wages = new List<decimal> { 10, 20 };

people.ForPair(wages, (p, w) => p.Wage = w);

Note however that this method cannot be used to modify the collection itself. This for example will not work:

List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };

listA.ForPair(listA, (c1, c2) => c1 = c2);  // Nothing will happen!

So in this case, the example in your own question is probably the best way.

Error: " 'dict' object has no attribute 'iteritems' "

I had a similar problem (using 3.5) and lost 1/2 a day to it but here is a something that works - I am retired and just learning Python so I can help my grandson (12) with it.

mydict2={'Atlanta':78,'Macon':85,'Savannah':72}
maxval=(max(mydict2.values()))
print(maxval)
mykey=[key for key,value in mydict2.items()if value==maxval][0]
print(mykey)
YEILDS; 
85
Macon

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.

There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.

Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:

  • std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
  • std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)

Meaning of = delete after function declaration

= delete is a feature introduce in C++11. As per =delete it will not allowed to call that function.

In detail.

Suppose in a class.

Class ABC{
 Int d;
 Public:
  ABC& operator= (const ABC& obj) =delete
  {

  }
};

While calling this function for obj assignment it will not allowed. Means assignment operator is going to restrict to copy from one object to another.

Using HTTPS with REST in Java

The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.

So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:

     public static String doPostSecureWithHeader(String url, String body, Map headers)
            throws Exception {
        log.info("start doPostSecureWithHeader " + url + " with param " + body);
        long startTime;
        long endTime;
        startTime = System.currentTimeMillis();
        Client client;
        client = Client.create();
        WebResource webResource;
        webResource = null;
        String output = null;
        try{
            SSLContext sslContext = null;
            SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
            sslContext = SSLContext.getInstance("SSL");
            sslContext
            .init(null,
                    new javax.net.ssl.TrustManager[] { secureRestClientTrustManager },
                    null);
            DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
            defaultClientConfig
            .getProperties()
            .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new com.sun.jersey.client.urlconnection.HTTPSProperties(
                            getHostnameVerifier(), sslContext));

            client = Client.create(defaultClientConfig);
            webResource = client.resource(url);

            if(headers!=null && headers.size()>0){
                for (Map.Entry entry : headers.entrySet()){
                    webResource.setProperty(entry.getKey(), entry.getValue());
                }
            }
            WebResource.Builder builder = 
                    webResource.accept("application/json");
            if(headers!=null && headers.size()>0){
                for (Map.Entry entry : headers.entrySet()){
                    builder.header(entry.getKey(), entry.getValue());
                }
            }

            ClientResponse response = builder
                    .post(ClientResponse.class, body);
            output = response.getEntity(String.class);
        }
        catch(Exception e){
            log.error(e.getMessage(),e);
            if(e.toString().contains("One or more of query value parameters are null")){
                output="-1";
            }
            if(e.toString().contains("401 Unauthorized")){
                throw e;
            }
        }
        finally {
            if (client!= null) {
                client.destroy();
            }
        }
        endTime = System.currentTimeMillis();
        log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output);
        return output;
    }

TypeError: expected a character buffer object - while trying to save integer to textfile

Just try the code below:

As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'

I hope this will help ;)

f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file 

x = f.readlines() #this command will read file lines

y = int(x)+1

print y
z = str(y) #making data as string to avoid buffer error
f.write(z)

f.close()

How to make vim paste from (and copy to) system's clipboard?

This would be the lines you need in your vimrc for this purpose:

set clipboard+=unnamed  " use the clipboards of vim and win
set paste               " Paste from a windows or from vim
set go+=a               " Visual selection automatically copied to the clipboard

What's the difference between `raw_input()` and `input()` in Python 3?

Python 2:

  • raw_input() takes exactly what the user typed and passes it back as a string.

  • input() first takes the raw_input() and then performs an eval() on it as well.

The main difference is that input() expects a syntactically correct python statement where raw_input() does not.

Python 3:

  • raw_input() was renamed to input() so now input() returns the exact string.
  • Old input() was removed.

If you want to use the old input(), meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input()).

Create a txt file using batch file in a specific folder

Changed the set to remove % as that will write to text file as Echo on or off

echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ; 
echo %txt% > "D:\Testing\dblank.txt"
exit

What is a handle in C++?

This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".

It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I'm afraid none of these solutions worked for me. Perhaps because I was using belongs_to in my create_table migration for a polymorphic association.

I'll add my code below and a link to the solution that helped me in case anyone else stumbles upon when searching for 'Index name is too long' in connection with polymorphic associations.

The following code did NOT work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true
    t.timestamps
  end
  add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end

This code DID work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }

    t.timestamps
  end
end

This is the SO Q&A that helped me out: https://stackoverflow.com/a/30366460/3258059

Take screenshots in the iOS simulator

First, run the app on simulator. Then, use command+s, or File -> Save Screenshot in Simulator to take necessary and appropriate shots. The screenshots will appear on your desktop by default.

What is the correct way to represent null XML elements?

There is no canonical answer, since XML fundamentally has no null concept. But I assume you want Xml/Object mapping (since object graphs have nulls); so the answer for you is "whatever your tool uses". If you write handling, that means whatever you prefer. For tools that use XML Schema, xsi:nil is the way to go. For most mappers, omitting matching element/attribute is the way to do it.

Combine Points with lines with ggplot2

The following example using the iris dataset works fine:

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
      id.vars = "Species")
ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +  
      geom_point() + geom_line()

enter image description here

How do you fadeIn and animate at the same time?

$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');

However, this doesn't appear to work on display: none elements (as fadeIn does). So, you might need to put this beforehand:

$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);

What's the "Content-Length" field in HTTP header?

The Content-Length header is a number denoting an the exact byte length of the HTTP body. The HTTP body starts immediately after the first empty line that is found after the start-line and headers.

Generally the Content-Length header is used for HTTP 1.1 so that the receiving party knows when the current response* has finished, so the connection can be reused for another request.

* ...or request, in the case of request methods that have a body, such as POST, PUT or PATCH

Alternatively, Content-Length header can be omitted and a chunked Transfer-Encoding header can be used.

If both Content-Length and Transfer-Encoding headers are missing, then at the end of the response the connection must be closed.

The following resource is a guide that I found very useful when learning about HTTP:

HTTP Made Really Easy.

Homebrew: Could not symlink, /usr/local/bin is not writable

I found for my particular setup the following commands worked

brew doctor

And then that showed me where my errors were, and then this slightly different command from the comment above.

sudo chown -R $(whoami) /usr/local/opt

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

keypress, ctrl+c (or some combo like that)

enter image description here

$(window).keypress("c", function(e) {
  if (!e.ctrlKey)
    return;

  console.info("CTRL +  C detected !");
});

_x000D_
_x000D_
$(window).keypress("c", function(e) {_x000D_
  if (!e.ctrlKey)_x000D_
    return;_x000D_
_x000D_
  $("div").show();_x000D_
});
_x000D_
/*https://gist.github.com/jeromyanglim/3952143 */_x000D_
_x000D_
kbd {_x000D_
  white-space: nowrap;_x000D_
  color: #000;_x000D_
  background: #eee;_x000D_
  border-style: solid;_x000D_
  border-color: #ccc #aaa #888 #bbb;_x000D_
  padding: 2px 6px;_x000D_
  -moz-border-radius: 4px;_x000D_
  -webkit-border-radius: 4px;_x000D_
  border-radius: 4px;_x000D_
  -moz-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
  -webkit-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;_x000D_
  background-color: #FAFAFA;_x000D_
  border-color: #CCCCCC #CCCCCC #FFFFFF;_x000D_
  border-style: solid solid none;_x000D_
  border-width: 1px 1px medium;_x000D_
  color: #444444;_x000D_
  font-family: 'Helvetica Neue', Helvetica, Arial, Sans-serif;_x000D_
  font-size: 11px;_x000D_
  font-weight: bold;_x000D_
  white-space: nowrap;_x000D_
  display: inline-block;_x000D_
  margin-bottom: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div style="display:none">_x000D_
  <kbd>CTRL</kbd> + <kbd>C</kbd> detected !_x000D_
</div>
_x000D_
_x000D_
_x000D_

Use of 'prototype' vs. 'this' in JavaScript?

Think about statically typed language, things on prototype are static and things on this are instance related.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

CMake unable to determine linker language with C++

I want to add another solution in case a library without any source files shall be build. Such libraries are also known as header only libraries. By default add_library expects at least one source file added or otherwise the mentioned error occurs. Since header only libraries are quite common, cmake has the INTERFACE keyword to build such libraries. The INTERFACE keyword is used as shown below and it eliminates the need for empty source files added to the library.

add_library(myLibrary INTERFACE)
target_include_directories(myLibrary INTERFACE {CMAKE_CURRENT_SOURCE_DIR})

The example above would build a header only library including all header files in the same directory as the CMakeLists.txt. Replace {CMAKE_CURRENT_SOURCE_DIR} with a path in case your header files are in a different directory than the CMakeLists.txt file.

Have a look at this blog post or the cmake documentation for further info regarding header only libraries and cmake.

What happens if you mount to a non-empty mount point with fuse?

force it with -l

    sudo umount -l ${HOME}/mount_dir

How to convert List<string> to List<int>?

Another way to accomplish this would be using a linq statement. The recomended answer did not work for me in .NetCore2.0. I was able to figure it out however and below would also work if you are using newer technology.

[HttpPost]
public ActionResult Report(FormCollection collection)
{
    var listofIDs = collection.ToList().Select(x => x.ToString());
    List<Dinner> dinners = new List<Dinner>();
    dinners = repository.GetDinners(listofIDs);
    return View(dinners);
}

How to loop through elements of forms with JavaScript?

A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach method is available. [...form.elements].forEach

Update: Array.from is a nicer alternative to spread Array.from(form.elements) it's slightly clearer behaviour.


An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"

_x000D_
_x000D_
const forms = document.querySelectorAll('form');
const form = forms[0];

Array.from(form.elements).forEach((input) => {
  console.log(input);
});
_x000D_
<div>
  <h1>Input Form Selection</h1>
  <form>
    <label>
      Foo
      <input type="text" placeholder="Foo" name="Foo" />
    </label>
    <label>
      Password
      <input type="password" placeholder="Password" />
    </label>
    <label>
      Foo
      <input type="text" placeholder="Bar" name="Bar" />
    </label>
    <span>Ts &amp; Cs</span>
    <input type="hidden" name="_id" />
    <input type="submit" name="_id" />
  </form>
</div>
_x000D_
_x000D_
_x000D_

Why are only final variables accessible in anonymous class?

Try this code,

Create Array List and put value inside that and return it :

private ArrayList f(Button b, final int a)
{
    final ArrayList al = new ArrayList();
    b.addClickHandler(new ClickHandler() {

         @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             al.add(b);
        }
    });
    return al;
}

Adding :default => true to boolean in existing Rails column

If you just made a migration, you can rollback and then make your migration again.

To rollback you can do as many steps as you want:

rake db:rollback STEP=1

Or, if you are using Rails 5.2 or newer:

rails db:rollback STEP=1

Then, you can just make the migration again:

def change
  add_column :profiles, :show_attribute, :boolean, default: true
end

Don't forget to rake db:migrate and if you are using heroku heroku run rake db:migrate

How do I block comment in Jupyter notebook?

I am using chrome, Linux Mint; and for commenting and dis-commenting bundle of lines:

Ctrl + /

Call a React component method from outside

With React17 you can use useImperativeHandle hook.

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef:

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.focus();
        }
    }));

    return <input ref={inputRef} ... />;
}

FancyInput = forwardRef(FancyInput);

In this example, a parent component that renders would be able to call inputRef.current.focus().

Fixed page header overlaps in-page anchors

I wasn't having any luck with the answer listed above and ended up using this solution which worked perfectly...

Create a blank span where you want to set your anchor.

<span class="anchor" id="section1"></span>
<div class="section"></div>

And apply the following class:

.anchor {
  display: block;
  height: 115px;       /* same height as header */
  margin-top: -115px;  /* same height as header */
  visibility: hidden;
}

This solution will work even if the sections have different colored backgrounds! I found the solution at this link.

angularjs getting previous route path

modification for the code above:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('prev path: ' + absOldUrl.$$route.originalPath);
});

Cross field validation with Hibernate Validator (JSR 303)

Solution realated with question: How to access a field which is described in annotation property

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Match {

    String field();

    String message() default "";
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MatchValidator.class)
@Documented
public @interface EnableMatchConstraint {

    String message() default "Fields must match!";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class MatchValidator implements  ConstraintValidator<EnableMatchConstraint, Object> {

    @Override
    public void initialize(final EnableMatchConstraint constraint) {}

    @Override
    public boolean isValid(final Object o, final ConstraintValidatorContext context) {
        boolean result = true;
        try {
            String mainField, secondField, message;
            Object firstObj, secondObj;

            final Class<?> clazz = o.getClass();
            final Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                if (field.isAnnotationPresent(Match.class)) {
                    mainField = field.getName();
                    secondField = field.getAnnotation(Match.class).field();
                    message = field.getAnnotation(Match.class).message();

                    if (message == null || "".equals(message))
                        message = "Fields " + mainField + " and " + secondField + " must match!";

                    firstObj = BeanUtils.getProperty(o, mainField);
                    secondObj = BeanUtils.getProperty(o, secondField);

                    result = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
                    if (!result) {
                        context.disableDefaultConstraintViolation();
                        context.buildConstraintViolationWithTemplate(message).addPropertyNode(mainField).addConstraintViolation();
                        break;
                    }
                }
            }
        } catch (final Exception e) {
            // ignore
            //e.printStackTrace();
        }
        return result;
    }
}

And how to use it...? Like this:

@Entity
@EnableMatchConstraint
public class User {

    @NotBlank
    private String password;

    @Match(field = "password")
    private String passwordConfirmation;
}

Barcode scanner for mobile phone for Website in form

We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web. http://berrywing.com/scantoweb.html

You can even embed a link or button to start the scanner yourself within your web page.

<a href="bwstw://startscanner">Link to start scanner</a>

The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan. http://berrywing.com/scantoweb/#htmlscanbutton

How to get the HTML's input element of "file" type to only accept pdf files?

The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.

This attribute forces the file dialog to display the required mime type only. But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.

So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.

But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.

Finally, you'll have to test the extension on the server side too. Same problem about the maximum allowed file size.

AmazonS3 putObject with InputStream length example

adding log4j-1.2.12.jar file has resolved the issue for me

How to Identify port number of SQL server

  1. Open Run in your system.

  2. Type %windir%\System32\cliconfg.exe

  3. Click on ok button then check that the "TCP/IP Network Protocol Default Value Setup" pop-up is open.

  4. Highlight TCP/IP under the Enabled protocols window.

  5. Click the Properties button.

  6. Enter the new port number, then click OK.

enter image description here

What does the "@" symbol do in Powershell?

You can also wrap the output of a cmdlet (or pipeline) in @() to ensure that what you get back is an array rather than a single item.

For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:

$results = @( dir c:\autoexec.bat)

One more thing... an empty array (like to initialize a variable) is denoted @().

Replace multiple strings at once

There is no way to do this in one method call, you'll have to either chain calls together, or write a function that manually does what you need.

var s = "<>\n";
s = s.replace("<", "&lt;");
s = s.replace(">", "&gt;");
s = s.replace("\n", "<br/>");

How to get the current date/time in Java

Have you looked at java.util.Date? It is exactly what you want.

How to pass parameters to $http in angularjs?

We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.

<input type="text" placeholder="Enter your Email" ng-model="email" required>

<input type="text" placeholder="Enter your password " ng-model="password" required> 

and in the js file w use $scope to access this data:

$scope.email="";
$scope.password="";

Controller function will be something like that:

 var app = angular.module('myApp', []);

    app.controller('assignController', function($scope, $http) {
      $scope.email="";
      $scope.password="";

      $http({
        method: "POST",
        url: "http://localhost:3000/users/sign_in",
        params: {email: $scope.email, password: $scope.password}

      }).then(function mySuccess(response) {
          // a string, or an object, carrying the response from the server.
          $scope.myRes = response.data;
          $scope.statuscode = response.status;

        }, function myError(response) {
          $scope.myRes = response.statusText;
      });
    });

creating json object with variables

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

How can I get the concatenation of two lists in Python without modifying either one?

you could always create a new list which is a result of adding two lists.

>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]

Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.

Access host database from a docker container

If you want access to a Docker container where there is a DB, you have to add a bash:

docker exec -it postgresql bash

postgresql is the container name.

Once inside, from the bash, access to DB e.g:

$psql -U postgres

PHP Fatal error: Call to undefined function json_decode()

With Ubuntu :

sudo apt-get install php5-json
sudo service php5-fpm restart

Amazon Linux: apt-get: command not found

I faced the same issue regarding apt-get: command not found here are the steps how I resolved it on ubuntu xenial

  • Search the appropriate version of apt from here (apt_1.4_amd64.deb for ubuntu xenial)

  • Download the apt.deb

    wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

  • Install the apt.deb package

    sudo dpkg -i apt_1.4_amd64.deb

Now we can easily run

sudo apt-get install htop

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Can CSS detect the number of children an element has?

NOTE: This solution will return the children of sets of certain lengths, not the parent element as you have asked. Hopefully, it's still useful.

Andre Luis came up with a method: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ Unfortunately, it only works in IE9 and above.

Essentially, you combine :nth-child() with other pseudo classes that deal with the position of an element. This approach allows you to specify elements from sets of elements with specific lengths.

For instance :nth-child(1):nth-last-child(3) matches the first element in a set while also being the 3rd element from the end of the set. This does two things: guarantees that the set only has three elements and that we have the first of the three. To specify the second element of the three element set, we'd use :nth-child(2):nth-last-child(2).


Example 1 - Select all list elements if set has three elements:

li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
    width: 33.3333%;
}

Example 1 alternative from Lea Verou:

li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}


Example 2 - target last element of set with three list elements:

li:nth-child(3):last-child {
    /* I'm the last of three */
}

Example 2 alternative:

li:nth-child(3):nth-last-child(1) {
    /* I'm the last of three */
}


Example 3 - target second element of set with four list elements:

li:nth-child(2):nth-last-child(3) {
    /* I'm the second of four */
}

Where is Maven's settings.xml located on Mac OS?

It doesn't exist at first. You have to create it in your home folder, /Users/usename/.m2/ (or ~/.m2)

For example :

alt text

How to remove line breaks from a file in Java?

You can use generic methods to replace any char with any char.

public static void removeWithAnyChar(String str, char replceChar,
        char replaceWith) {
    char chrs[] = str.toCharArray();
    int i = 0;
    while (i < chrs.length) {

        if (chrs[i] == replceChar) {
            chrs[i] = replaceWith;
        }
        i++;
    }

}

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

Here's the exact definition of UsedRange (MSDN reference) :

Every Worksheet object has a UsedRange property that returns a Range object representing the area of a worksheet that is being used. The UsedRange property represents the area described by the farthest upper-left and farthest lower-right nonempty cells in a worksheet and includes all cells in between.

So basically, what that line does is :

  1. .UsedRange -> "Draws" a box around the outer-most cells with content inside.
  2. .Columns -> Selects the entire columns of those cells
  3. .Count -> Returns an integer corresponding to how many columns there are (in this selection)
  4. - 8 -> Subtracts 8 from the previous integer.

I assume VBA calculates the UsedRange by finding the non-empty cells with lowest and highest index values.

Most likely, you're getting an error because the number of lines in your range is smaller than 3, and therefore the number returned is negative.

A method to count occurrences in a list

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

AWK to print field $2 first, then field $1

Use a dot or a pipe as the field separator:

awk -v FS='[.|]' '{
    printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END

gives:

Emailclient [email protected]
Socialsite [email protected]

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

Get Application Directory

If you're trying to get access to a file, try the openFileOutput() and openFileInput() methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File objects altogether which is a pretty clean solution.

"Fatal error: Unable to find local grunt." when running "grunt" command

I think you have to add grunt to your package.json file. See this link.

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

Eclipse C++: Symbol 'std' could not be resolved

This worked for me on Eclipse IDE for C/C++ Developers Version: 2020-03 (4.15.0) Build id: 20200313-1211. Also, my code is cross-compiled.

  1. Create a new project making sure it's created as a cross-compiled solution. You have to add the /usr/bin directory that matches your cross-compiler location.
  2. Add the C and C++ headers for the cross-compiler in the Project Properties.
  3. For C: Project > Properties > C/C++ General > Paths and Symbols > Includes > GNU C. Add... -> The path to your /usr/include directory from your cross-compiler.
  4. For C++: Project > Properties > C/C++ General > Paths and Symbols > Includes > GNU C++. Add... -> The path to your /usr/include/c++/ directory from your cross-compiler.
  5. If you don't know your gcc version, type this in a console (make sure it's your cross gcc binary):

    gcc -v

  6. Modify the dialect for the cross-compilers (this was the trick).

  7. For C: Project > Properties > C/C++ Build > Settings > Tool Settings > Cross GCC Compiler > Dialect. Set to ISO C99 (-std=C99) or whatever fits your C files standard.
  8. For C++: Project > Properties > C/C++ Build > Settings > Tool Settings > Cross G++ Compiler > Dialect. Set to ISO C++14 (-std=c++14) or whatever fits your C++ files standard.
  9. If needed, re-index all your project by right-clicking the project > Index > Rebuild.

How to use `subprocess` command with pipes

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

How to pass the values from one jsp page to another jsp without submit button?

I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.

You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.

Or else the easiest you could do is use sessions.

<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>

<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">

<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>


$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});

This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/

MySQL: Invalid use of group function

You need to use HAVING, not WHERE.

The difference is: the WHERE clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT function.

HAVING is like WHERE, only it happens after the COUNT value has been computed, so it'll work as you expect. Rewrite your subquery as:

(                  -- where that pid is in the set:
SELECT c2.pid                  -- of pids
FROM Catalog AS c2             -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)

Open JQuery Datepicker by clicking on an image w/ no input field

To change the "..." when the mouse hovers over the calendar icon, You need to add the following in the datepicker options:

    showOn: 'button',
    buttonText: 'Click to show the calendar',
    buttonImageOnly: true, 
    buttonImage: 'images/cal2.png',

Xcode/Simulator: How to run older iOS version?

The simulator CANNOT be downloaded from:

Xcode -> Preferences -> Downloads

Only the iOS devices symbols. As this option says:

This package includes information and symbols that Xcode needs for debugging your app on iOS devices running versions of iOS prior to iOS 4.2. If you intend to debug your app on a device running one of these versions of iOS you should install this package.

That is, you need an iOS 4.2 device to test an iOS 4.2 application

Convert a Python list with strings all to lowercase or uppercase

mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print(list(map(lambda x: x.lower(), mylist)))
print(list(map(lambda x: x.upper(), mylist)))

SQL Server - after insert trigger - update another column in the same table

Yes, it will recursively call your trigger unless you turn the recursive triggers setting off:

ALTER DATABASE db_name SET RECURSIVE_TRIGGERS OFF 

MSDN has a good explanation of the behavior at http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx under the Recursive Triggers heading.

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

How to change line-ending settings

If you want to convert back the file formats which have been changed to UNIX Format from PC format.

(1)You need to reinstall tortoise GIT and in the "Line Ending Conversion" Section make sure that you have selected "Check out as is - Check in as is"option.

(2)and keep the remaining configurations as it is.

(3)once installation is done

(4)write all the file extensions which are converted to UNIX format into a text file (extensions.txt).

ex:*.dsp
   *.dsw

(5) copy the file into your clone Run the following command in GITBASH

while read -r a;
do
find . -type f -name "$a" -exec dos2unix {} \;
done<extension.txt

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

How to make layout with rounded corners..?

If you would like to make your layout rounded, it is best to use the CardView, it provided many features to make the design beautiful.

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="5dp">
      <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".3"
                android:text="@string/quote_code"
                android:textColor="@color/white"
                android:textSize="@dimen/text_head_size" />
      </LinearLayout>
</android.support.v7.widget.CardView>

With this card_view:cardCornerRadius="5dp", you can change the radius.

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

With these two steps we can check if it LL(1) or not. Both of them have to be satisfied.

1.If we have the production:A->a1|a2|a3|a4|.....|an. Then,First(a(i)) intersection First(a(j)) must be phi(empty set)[a(i)-a subscript i.]

2.For every non terminal 'A',if First(A) contains epsilon Then First(A) intersection Follow(A) must be phi(empty set).

Finding height in Binary Search Tree

Set a tempHeight as a static variable(initially 0).

static void findHeight(Node node, int count) {

    if (node == null) {
        return;
    }
    if ((node.right == null) && (node.left == null)) {
        if (tempHeight < count) {
            tempHeight = count;

        }

    }

    findHeight(node.left, ++count);
    count--; //reduce the height while traversing to a different branch
    findHeight(node.right, ++count);

}

PHP's array_map including keys

With PHP5.3 or later:

$test_array = array("first_key" => "first_value", 
                    "second_key" => "second_value");

var_dump(
    array_map(
        function($key) use ($test_array) { return "$key loves ${test_array[$key]}"; },
        array_keys($test_array)
    )
);

Are the shift operators (<<, >>) arithmetic or logical in C?

TL;DR

Consider i and n to be the left and right operands respectively of a shift operator; the type of i, after integer promotion, be T. Assuming n to be in [0, sizeof(i) * CHAR_BIT) — undefined otherwise — we've these cases:

| Direction  |   Type   | Value (i) | Result                   |
| ---------- | -------- | --------- | ------------------------ |
| Right (>>) | unsigned |    = 0    | -8 ? (i ÷ 2n)            |
| Right      | signed   |    = 0    | -8 ? (i ÷ 2n)            |
| Right      | signed   |    < 0    | Implementation-defined†  |
| Left  (<<) | unsigned |    = 0    | (i * 2n) % (T_MAX + 1)   |
| Left       | signed   |    = 0    | (i * 2n) ‡               |
| Left       | signed   |    < 0    | Undefined                |

† most compilers implement this as arithmetic shift
‡ undefined if value overflows the result type T; promoted type of i


Shifting

First is the difference between logical and arithmetic shifts from a mathematical viewpoint, without worrying about data type size. Logical shifts always fills discarded bits with zeros while arithmetic shift fills it with zeros only for left shift, but for right shift it copies the MSB thereby preserving the sign of the operand (assuming a two's complement encoding for negative values).

In other words, logical shift looks at the shifted operand as just a stream of bits and move them, without bothering about the sign of the resulting value. Arithmetic shift looks at it as a (signed) number and preserves the sign as shifts are made.

A left arithmetic shift of a number X by n is equivalent to multiplying X by 2n and is thus equivalent to logical left shift; a logical shift would also give the same result since MSB anyway falls off the end and there's nothing to preserve.

A right arithmetic shift of a number X by n is equivalent to integer division of X by 2n ONLY if X is non-negative! Integer division is nothing but mathematical division and round towards 0 (trunc).

For negative numbers, represented by two's complement encoding, shifting right by n bits has the effect of mathematically dividing it by 2n and rounding towards -8 (floor); thus right shifting is different for non-negative and negative values.

for X = 0, X >> n = X / 2n = trunc(X ÷ 2n)

for X < 0, X >> n = floor(X ÷ 2n)

where ÷ is mathematical division, / is integer division. Let's look at an example:

37)10 = 100101)2

37 ÷ 2 = 18.5

37 / 2 = 18 (rounding 18.5 towards 0) = 10010)2 [result of arithmetic right shift]

-37)10 = 11011011)2 (considering a two's complement, 8-bit representation)

-37 ÷ 2 = -18.5

-37 / 2 = -18 (rounding 18.5 towards 0) = 11101110)2 [NOT the result of arithmetic right shift]

-37 >> 1 = -19 (rounding 18.5 towards -8) = 11101101)2 [result of arithmetic right shift]

As Guy Steele pointed out, this discrepancy has led to bugs in more than one compiler. Here non-negative (math) can be mapped to unsigned and signed non-negative values (C); both are treated the same and right-shifting them is done by integer division.

So logical and arithmetic are equivalent in left-shifting and for non-negative values in right shifting; it's in right shifting of negative values that they differ.

Operand and Result Types

Standard C99 §6.5.7:

Each of the operands shall have integer types.

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behaviour is undefined.

short E1 = 1, E2 = 3;
int R = E1 << E2;

In the above snippet, both operands become int (due to integer promotion); if E2 was negative or E2 = sizeof(int) * CHAR_BIT then the operation is undefined. This is because shifting more than the available bits is surely going to overflow. Had R been declared as short, the int result of the shift operation would be implicitly converted to short; a narrowing conversion, which may lead to implementation-defined behaviour if the value is not representable in the destination type.

Left Shift

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and non-negative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behaviour is undefined.

As left shifts are the same for both, the vacated bits are simply filled with zeros. It then states that for both unsigned and signed types it's an arithmetic shift. I'm interpreting it as arithmetic shift since logical shifts don't bother about the value represented by the bits, it just looks at it as a stream of bits; but the standard talks not in terms of bits, but by defining it in terms of the value obtained by the product of E1 with 2E2.

The caveat here is that for signed types the value should be non-negative and the resulting value should be representable in the result type. Otherwise the operation is undefined. The result type would be the type of the E1 after applying integral promotion and not the destination (the variable which is going to hold the result) type. The resulting value is implicitly converted to the destination type; if it is not representable in that type, then the conversion is implementation-defined (C99 §6.3.1.3/3).

If E1 is a signed type with a negative value then the behaviour of left shifting is undefined. This is an easy route to undefined behaviour which may easily get overlooked.

Right Shift

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Right shift for unsigned and signed non-negative values are pretty straight forward; the vacant bits are filled with zeros. For signed negative values the result of right shifting is implementation-defined. That said, most implementations like GCC and Visual C++ implement right-shifting as arithmetic shifting by preserving the sign bit.

Conclusion

Unlike Java, which has a special operator >>> for logical shifting apart from the usual >> and <<, C and C++ have only arithmetic shifting with some areas left undefined and implementation-defined. The reason I deem them as arithmetic is due to the standard wording the operation mathematically rather than treating the shifted operand as a stream of bits; this is perhaps the reason why it leaves those areas un/implementation-defined instead of just defining all cases as logical shifts.

Installing a plain plugin jar in Eclipse 3.5

go to Help -> Install New Software... -> Add -> Archive.... Done.

POST data in JSON format

Here is an example using jQuery...

 <head>
   <title>Test</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
   <script type="text/javascript">
     $(function() {
       var frm = $(document.myform);
       var dat = JSON.stringify(frm.serializeArray());

       alert("I am about to POST this:\n\n" + dat);

       $.post(
         frm.attr("action"),
         dat,
         function(data) {
           alert("Response: " + data);
         }
       );
     });
   </script>
</head>

The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

Apache redirect to another port

Apache supports name based and IP based virtual hosts. It looks like you are using both, which is probably not what you need.

I think you're actually trying to set up name-based virtual hosting, and for that you don't need to specify the IP address.

Try < VirtualHost *:80> to bind to all IP addresses, unless you really want ip based virtual hosting. This may be the case if the server has several IP addresses, and you want to serve different sites on different addresses. The most common setup is (I would guess) name based virtual hosts.

What are the differences between type() and isinstance()?

The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()'s second parameter may be a tuple:

if isinstance(b, (str, unicode)):
    do_something_else()

or, using the basestring abstract class:

if isinstance(b, basestring):
    do_something_else()

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

How do I escape spaces in path for scp copy in Linux?

Also you can do something like:

scp foo@bar:"\"apath/with spaces in it/\""

The first level of quotes will be interpreted by scp and then the second level of quotes will preserve the spaces.

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I ran into this myself when I wanted to make a thor command under Windows.

To avoid having that message output everytime I ran my thor application I temporarily muted warnings while loading thor:

begin
  original_verbose = $VERBOSE
  $VERBOSE = nil
  require "thor"
ensure
  $VERBOSE = original_verbose
end

That saved me from having to edit third party source files.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

Java code To convert byte to Hexadecimal

BigInteger n = new BigInteger(byteArray);
String hexa = n.toString(16));

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

How to get the <html> tag HTML with JavaScript / jQuery?

if you want to get an attribute of an HTML element with jQuery you can use .attr();

so $('html').attr('someAttribute'); will give you the value of someAttribute of the element html

http://api.jquery.com/attr/

Additionally:

there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes

that allows you to get all attributes from an HTML element

How to change the output color of echo in Linux

I've written swag to achieve just that.

You can just do

pip install swag

Now you can install all the escape commands as txt files to a given destination via:

swag install -d <colorsdir>

Or even easier via:

swag install

Which will install the colors to ~/.colors.

Either you use them like this:

echo $(cat ~/.colors/blue.txt) This will be blue

Or this way, which I find actually more interesting:

swag print -c red -t underline "I will turn red and be underlined"

Check it out on asciinema!

Check if a number is int or float

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Is it safe to delete the "InetPub" folder?

it is safe to delete the inetpub it is only a cache.

When should I use the new keyword in C++?

The short answer is yes the "new" keyword is incredibly important as when you use it the object data is stored on the heap as opposed to the stack, which is most important!

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to join three table by laravel eloquent model

Try:

$articles = DB::table('articles')
            ->select('articles.id as articles_id', ..... )
            ->join('categories', 'articles.categories_id', '=', 'categories.id')
            ->join('users', 'articles.user_id', '=', 'user.id')

            ->get();

python modify item in list, save back in list

You could do this:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

C#: How to add subitems in ListView

Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different. we should add this

listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true; 
listView1.FullRowSelect = true;

Convert string to date then format the date

Tested this code

java.text.DateFormat formatter = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date newDate = new java.util.Date();
System.out.println(formatter.format(newDate ));

http://download.oracle.com/javase/1,5.0/docs/api/java/text/SimpleDateFormat.html

Is there a numpy builtin to reject outliers from a list

An alternative is to make a robust estimation of the standard deviation (assuming Gaussian statistics). Looking up online calculators, I see that the 90% percentile corresponds to 1.2815σ and the 95% is 1.645σ (http://vassarstats.net/tabs.html?#z)

As a simple example:

import numpy as np

# Create some random numbers
x = np.random.normal(5, 2, 1000)

# Calculate the statistics
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Add a few large points
x[10] += 1000
x[20] += 2000
x[30] += 1500

# Recalculate the statistics
print()
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Measure the percentile intervals and then estimate Standard Deviation of the distribution, both from median to the 90th percentile and from the 10th to 90th percentile
p90 = np.percentile(x, 90)
p10 = np.percentile(x, 10)
p50 = np.median(x)
# p50 to p90 is 1.2815 sigma
rSig = (p90-p50)/1.2815
print("Robust Sigma=", rSig)

rSig = (p90-p10)/(2*1.2815)
print("Robust Sigma=", rSig)

The output I get is:

Mean=  4.99760520022
Median=  4.95395274981
Max/Min= 11.1226494654   -2.15388472011
Sigma= 1.976629928
90th Percentile 7.52065379649

Mean=  9.64760520022
Median=  4.95667658782
Max/Min= 2205.43861943   -2.15388472011
Sigma= 88.6263902244
90th Percentile 7.60646688694

Robust Sigma= 2.06772555531
Robust Sigma= 1.99878292462

Which is close to the expected value of 2.

If we want to remove points above/below 5 standard deviations (with 1000 points we would expect 1 value > 3 standard deviations):

y = x[abs(x - p50) < rSig*5]

# Print the statistics again
print("Mean= ", np.mean(y))
print("Median= ", np.median(y))
print("Max/Min=", y.max(), " ", y.min())
print("StdDev=", np.std(y))

Which gives:

Mean=  4.99755359935
Median=  4.95213030447
Max/Min= 11.1226494654   -2.15388472011
StdDev= 1.97692712883

I have no idea which approach is the more efficent/robust

Condition within JOIN or WHERE

I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.

I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

Formatting PowerShell Get-Date inside string

"This is my string with date in specified format $($theDate.ToString('u'))"

or

"This is my string with date in specified format $(Get-Date -format 'u')"

The sub-expression ($(...)) can include arbitrary expressions calls.

MSDN Documents both standard and custom DateTime format strings.

Specify JDK for Maven to use

As u said "Plus, I don't want to use 1.6 for all maven builds."....So better I will say modify your pom file and specify which jdk version to use.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>1.9</source>
                <target>1.9</target>
            </configuration>
        </plugin>
    </plugins>
</build>

It will ensure that your particular project uses that version of jdk.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

If you want to set custom volume icon then use below command

/*Add a drive icon*/
cp "/Volumes/customIcon.icns" "/Volumes/dmgName/.VolumeIcon.icns"  


/*SetFile -c icnC will change the creator of the file to icnC*/
SetFile -c icnC /<your path>/.VolumeIcon.icns

Now create read/write dmg

/*to set custom icon attribute*/
SetFile -a C /Volumes/dmgName

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

How can I handle the warning of file_get_contents() function in PHP?

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

I got this issue on a Web API project. Finally figured out that it was in my "///" method comments. I have these comments set to auto-generate documentation for the API methods. Something in my comments made it go crazy. I deleted all the carriage returns, special characters, etc. Not really sure which thing it didn't like, but it worked.

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

Android: show/hide a view using an animation

This can reasonably be achieved in a single line statement in API 12 and above. Below is an example where v is the view you wish to animate;

v.animate().translationXBy(-1000).start();

This will slide the View in question off to the left by 1000px. To slide the view back onto the UI we can simply do the following.

v.animate().translationXBy(1000).start();

I hope someone finds this useful.

Convert pandas data frame to series

It's not smart enough to realize it's still a "vector" in math terms.

Say rather that it's smart enough to recognize a difference in dimensionality. :-)

I think the simplest thing you can do is select that row positionally using iloc, which gives you a Series with the columns as the new index and the values as the values:

>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
   a0  a1  a2  a3  a4
0   0   1   2   3   4
>>> df.iloc[0]
a0    0
a1    1
a2    2
a3    3
a4    4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>

How do I run two commands in one line in Windows CMD?

& is the Bash equivalent for ; ( run commands) and && is the Bash equivalent of && (run commands only when the previous has not caused an error).

How to generate .env file for laravel?

There's another explanation for why .env doesn't exist, and it happens when you move all the Laravel files.

Take this workflow: in your project directory you do laravel new whatever, Laravel is installed in whatever, you do mv * .. to move all the files to your project folder, and you remove whatever. The problem is, mv doesn't move hidden files by default, so the .env files are left behind, and are removed!

Declare and Initialize String Array in VBA

In the specific case of a String array you could initialize the array using the Split Function as it returns a String array rather than a Variant array:

Dim arrWsNames() As String
arrWsNames = Split("Value1,Value2,Value3", ",")

This allows you to avoid using the Variant data type and preserve the desired type for arrWsNames.

How to discover number of *logical* cores on Mac OS X?

You can do this using the sysctl utility:

sysctl -n hw.ncpu

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

Nginx -- static file serving confusion with root & alias

as say as @treecoder

In case of the root directive, full path is appended to the root including the location part, whereas in case of the alias directive, only the portion of the path NOT including the location part is appended to the alias.

A picture is worth a thousand words

for root:

enter image description here

for alias:

enter image description here

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Does MS SQL Server's "between" include the range boundaries?

It does includes boundaries.

declare @startDate date = cast('15-NOV-2016' as date) 
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT    c1
2016-11-15
2016-11-20
2016-11-30


declare @r1 int  = 10
declare @r2 int  = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15

Why is the GETDATE() an invalid identifier

I think you want SYSDATE, not GETDATE(). Try it:

UPDATE TableName SET LastModifiedDate = (SELECT SYSDATE FROM DUAL);

What is the difference between encode/decode?

The simple answer is that they are the exact opposite of each other.

The computer uses the very basic unit of byte to store and process information; it is meaningless for human eyes.

For example,'\xe4\xb8\xad\xe6\x96\x87' is the representation of two Chinese characters, but the computer only knows (meaning print or store) it is Chinese Characters when they are given a dictionary to look for that Chinese word, in this case, it is a "utf-8" dictionary, and it would fail to correctly show the intended Chinese word if you look into a different or wrong dictionary (using a different decoding method).

In the above case, the process for a computer to look for Chinese word is decode().

And the process of computer writing the Chinese into computer memory is encode().

So the encoded information is the raw bytes, and the decoded information is the raw bytes and the name of the dictionary to reference (but not the dictionary itself).

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

- First to me Iterating and Looping are 2 different things.

Eg: Increment a variable till 5 is Looping.

    int count = 0;

    for (int i=0 ; i<5 ; i++){

        count = count + 1;

   }

Eg: Iterate over the Array to print out its values, is about Iteration

    int[] arr = {5,10,15,20,25};

    for (int i=0 ; i<arr.length ; i++){

        System.out.println(arr[i]);

   }

Now about all the Loops:

- Its always better to use For-Loop when you know the exact nos of time you gonna Loop, and if you are not sure of it go for While-Loop. Yes out there many geniuses can say that it can be done gracefully with both of them and i don't deny with them...but these are few things which makes me execute my program flawlessly...

For Loop :

int sum = 0; 

for (int i = 1; i <= 100; i++) {

  sum += i; 

}

 System.out.println("The sum is " + sum);

The Difference between While and Do-While is as Follows :

- While is a Entry Control Loop, Condition is checked in the Beginning before entering the loop.

- Do-While is a Exit Control Loop, Atleast once the block is always executed then the Condition is checked.

While Loop :

int sum = 0; 
int i = 0;       // i is 0 Here

    while (i<100) {

      sum += i; 
      i++;

    }

  System.out.println("The sum is " + sum);

do-While :

int sum = 0; 
int i = 0;      // i is 0 Here

    do{ 

      sum += i; 
       i++
    }while(i < 100; );

     System.out.println("The sum is " + sum);

From Java 5 we also have For-Each Loop to iterate over the Collections, even its handy with Arrays.

ArrayList<String> arr = new ArrayList<String>();

arr.add("Vivek");
arr.add("Is");
arr.add("Good");
arr.add("Boy");

for (String str : arr){         // str represents the value in each index of arr

    System.out.println(str);     

 }

Regex that matches integers in between whitespace or start/end of string only

Try /^(?:-?[1-9]\d*$)|(?:^0)$/.

It matches positive, negative numbers as well as zeros.

It doesn't match input like 00, -0, +0, -00, +00, 01.

Online testing available at http://rubular.com/r/FlnXVL6SOq

How do I implement interfaces in python?

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

Difference between natural join and inner join

Inner join and natural join are almost same but there is a slight difference between them. The difference is in natural join no need to specify condition but in inner join condition is obligatory. If we do specify the condition in inner join , it resultant tables is like a cartesian product.

Index inside map() function

Array.prototype.map() index:

One can access the index Array.prototype.map() via the second argument of the callback function. Here is an example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
_x000D_
const map = array.map((x, index) => {_x000D_
  console.log(index);_x000D_
  return x + index;_x000D_
});_x000D_
_x000D_
console.log(map);
_x000D_
_x000D_
_x000D_

Other arguments of Array.prototype.map():

  • The third argument of the callback function exposes the array on which map was called upon
  • The second argument of Array.map() is a object which will be the this value for the callback function. Keep in mind that you have to use the regular function keyword in order to declare the callback since an arrow function doesn't have its own binding to the this keyword.

For example:

_x000D_
_x000D_
const array = [1, 2, 3, 4];_x000D_
_x000D_
const thisObj = {prop1: 1}_x000D_
_x000D_
_x000D_
const map = array.map( function (x, index, array) {_x000D_
  console.log(array);_x000D_
  console.log(this)_x000D_
}, thisObj);
_x000D_
_x000D_
_x000D_

How to find server name of SQL Server Management Studio

given the following examples

  • SQL Instance Name: MSSQLSERVER
  • Port: 1433
  • Hostname: MyKitchenPC
  • IPv4: 10.242.137.227
  • DNS Suffix: dir.svc.mykitchencompany.com

here are your possible servernames:

  • localhost\MSSQLSERVER
  • localhost,1433\MSSQLSERVER
  • MyKitchenPC,1433\MSSQLSERVER
  • 10.242.137.227,1433\MSSQLSERVER
  • MyKitchenPC.dir.svc.mykitchencompany.com,1433\MSSQLSERVER

How to retrieve an element from a set without removing it?

Since you want a random element, this will also work:

>>> import random
>>> s = set([1,2,3])
>>> random.sample(s, 1)
[2]

The documentation doesn't seem to mention performance of random.sample. From a really quick empirical test with a huge list and a huge set, it seems to be constant time for a list but not for the set. Also, iteration over a set isn't random; the order is undefined but predictable:

>>> list(set(range(10))) == range(10)
True 

If randomness is important and you need a bunch of elements in constant time (large sets), I'd use random.sample and convert to a list first:

>>> lst = list(s) # once, O(len(s))?
...
>>> e = random.sample(lst, 1)[0] # constant time

How to convert numbers to words without using num2word library?

Convert numbers to words:
Here is an example in which numbers have been converted into words using the dictionary.

string = input("Enter a string: ")
my_dict = {'0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'}
for item in string:
  if item in my_dict.keys():
    string = string.replace(item, my_dict[item])
print(string)

Output

Print PHP Call Stack

I have adapted Don Briggs's answer above to use internal error logging instead of public printing, which may be your big concern when working on a live server. Also, added few more modifications like option to include full file path instead of basic name (because, there could be files with same name in different paths), and also (for those who require it) a complete node stack output:

class debugUtils {
    public static function callStack($stacktrace) {
        error_log(str_repeat("=", 100));
        $i = 1;
        foreach($stacktrace as $node) {
            // uncomment next line to debug entire node stack
            // error_log(print_r($node, true));
            error_log( $i . '.' . ' file: ' .$node['file'] . ' | ' . 'function: ' . $node['function'] . '(' . ' line: ' . $node['line'] . ')' );
            $i++;
        }
        error_log(str_repeat("=", 100));
    } 
}

// call debug stack
debugUtils::callStack(debug_backtrace());

Make sure that the controller has a parameterless public constructor error

I had the same issue and I resolved it by making changes in the UnityConfig.cs file In order to resolve the dependency issue in the UnityConfig.cs file you have to add:

public static void RegisterComponents()    
{
    var container = new UnityContainer();
    container.RegisterType<ITestService, TestService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

Keep only date part when using pandas.to_datetime

Just giving a more up to date answer in case someone sees this old post.

Adding "utc=False" when converting to datetime will remove the timezone component and keep only the date in a datetime64[ns] data type.

pd.to_datetime(df['Date'], utc=False)

You will be able to save it in excel without getting the error "ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel."

enter image description here

How do I prevent and/or handle a StackOverflowException?

By the looks of it, apart from starting another process, there doesn't seem to be any way of handling a StackOverflowException. Before anyone else asks, I tried using AppDomain, but that didn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;

namespace StackOverflowExceptionAppDomainTest
{
    class Program
    {
        static void recrusiveAlgorithm()
        {
            recrusiveAlgorithm();
        }
        static void Main(string[] args)
        {
            if(args.Length>0&&args[0]=="--child")
            {
                recrusiveAlgorithm();
            }
            else
            {
                var domain = AppDomain.CreateDomain("Child domain to test StackOverflowException in.");
                domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { "--child" });
                domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                {
                    Console.WriteLine("Detected unhandled exception: " + e.ExceptionObject.ToString());
                };
                while (true)
                {
                    Console.WriteLine("*");
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

If you do end up using the separate-process solution, however, I would recommend using Process.Exited and Process.StandardOutput and handle the errors yourself, to give your users a better experience.