Programs & Examples On #Dbf

ISAM database format originally created in dBase but used by many other systems like `Clipper` and `FoxPro` and still widely used for information interchange.

Provide schema while reading csv file as a dataframe

// import Library
import java.io.StringReader ;

import au.com.bytecode.opencsv.CSVReader

//filename

var train_csv = "/Path/train.csv";

//read as text file

val train_rdd = sc.textFile(train_csv)   

//use string reader to convert in proper format

var full_train_data  = train_rdd.map{line =>  var csvReader = new CSVReader(new StringReader(line)) ; csvReader.readNext();  }   

//declares  types

type s = String

// declare case class for schema

case class trainSchema (Loan_ID :s ,Gender :s, Married :s, Dependents :s,Education :s,Self_Employed :s,ApplicantIncome :s,CoapplicantIncome :s,
    LoanAmount :s,Loan_Amount_Term :s, Credit_History :s, Property_Area :s,Loan_Status :s)

//create DF RDD with custom schema 

var full_train_data_with_schema = full_train_data.mapPartitionsWithIndex{(idx,itr)=> if (idx==0) itr.drop(1); 
                     itr.toList.map(x=> trainSchema(x(0),x(1),x(2),x(3),x(4),x(5),x(6),x(7),x(8),x(9),x(10),x(11),x(12))).iterator }.toDF

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

An instance might be corrupted or not updated properly.

Try these Commands:

C:\>sqllocaldb stop MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" stopped.
 
C:\>sqllocaldb delete MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" deleted.
 
C:\>sqllocaldb create MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" created with version 13.0.1601.5.
 
C:\>sqllocaldb start MSSQLLocalDB
LocalDB instance "MSSQLLocalDB" started.

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

How to create a connection string in asp.net c#

It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot: Solution

Failed to install Python Cryptography package with PIP and setup.py

I resolved this by upgrading from cryptography 1.9 to 2.4.2

git status shows fatal: bad object HEAD

This happened because by mistake I removed some core file of GIT. Try this its worked for me.

re-initialize git

git init

fetch data from remote

git fetch

Now check all your changes and git status by

git status

What is "Connect Timeout" in sql server connection string?

Maximum time between connection request and a timeout error. When the client tries to make a connection, if the timeout wait limit is reached, it will stop trying and raise an error.

nodeJs callbacks simple example

_x000D_
_x000D_
//delay callback function_x000D_
function delay (seconds, callback){_x000D_
    setTimeout(() =>{_x000D_
      console.log('The long delay ended');_x000D_
      callback('Task Complete');_x000D_
    }, seconds*1000);_x000D_
}_x000D_
//Execute delay function_x000D_
delay(1, res => {  _x000D_
    console.log(res);  _x000D_
})
_x000D_
_x000D_
_x000D_

C# - Create SQL Server table programmatically

You haven't mentioned the Initial catalog name in the connection string. Give your database name as Initial Catalog name.

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

None of the other answers seemed correct in my case, however I found the real answer here

My id_rsa file was already in PEM format, I just needed to add the .pem extension to the filename.

Thanks to

The possible options to the openssl rsa -inform parameter are one of: PEM DER

A PEM encoded file is a plain-text encoding that looks something like:

-----BEGIN RSA PRIVATE KEY-----
MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
-----END RSA PRIVATE KEY-----

While DER is a binary encoding format.

Can't install via pip because of egg_info error

In my case, I had to uninstall pip and reinstall it. So I could install my specific version.

sudo apt-get purge --auto-remove python-pip
sudo easy_install pip 

Cannot attach the file *.mdf as database

I found that commenting out the context section used to initialise the database resolved the problem. Havnt had time to find out what was wrong with the seeding statements yet, but removing the seeding resolved the problem.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

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

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

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

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

How to define a Sql Server connection string to use in VB.NET?

Use the following Imports

Imports System.Data.SqlClient
Imports System.Data.Sql

Public SQLConn As New SqlConnection With {.ConnectionString = "Server=Desktop1[enter image description here][1];Database=Infostudio; Trusted_Connection=true;"}

Full string: enter image description here

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I was getting the xml as a String and using xml.getBytes() and getting this error. Changing to xml.getBytes(Charset.forName("UTF-8")) worked for me.

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

How to run multiple SQL commands in a single SQL connection?

Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection

public static class SQLTest
    {
        public static void NpgsqlCommand()
        {
            using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
            {
                NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
                NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
                command1.Connection.Open();
                command1.ExecuteNonQuery();
                command2.ExecuteNonQuery();
                command2.Connection.Close();
            }
        }
    }

Implement paging (skip / take) functionality with this query

SQL 2008

Radim Köhler's answer works, but here is a shorter version:

select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10

Source: https://forums.asp.net/post/4033909.aspx

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I tried several things, finally what worked for me was to delete (and move to trash) the .xib file in question. Then re-create it. To make things easier, I copied the stuff in the .xib temporarily to another .xib, then copied it back into the newly created one.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Uploading an Excel sheet and importing the data into SQL Server database

    public async Task<HttpResponseMessage> PostFormDataAsync()    //async is used for defining an asynchronous method
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        var fileLocation = "";
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);  //Helps in HTML file uploads to write data to File Stream
        try
        {
            // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
                var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
                File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
                fileLocation = file.LocalFileName + filePath; //Complete file location
            }
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
            return response;
}
catch (System.Exception e)
    {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
public void ReadFromExcel()
{
try
        {
            DataTable sheet1 = new DataTable();
            OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
            csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            csbuilder.DataSource = fileLocation;
            csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            string selectSql = @"SELECT * FROM [Sheet1$]";
            using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
            {
                connection.Open();
                adapter.Fill(sheet1);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }          
}

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...

or pdb

Celery Received unregistered task of type (run example)

My 2 cents

I was getting this in a docker image using alpine. The django settings referenced /dev/log for logging to syslog. The django app and celery worker were both based on the same image. The entrypoint of the django app image was launching syslogd on start, but the one for the celery worker was not. This was causing things like ./manage.py shell to fail because there wouldn't be any /dev/log. The celery worker was not failing. Instead, it was silently just ignoring the rest of the app launch, which included loading shared_task entries from applications in the django project

How do I connect to an MDF database file?

string sqlCon = @"Data Source=.\SQLEXPRESS;" +
                @"AttachDbFilename=|DataDirectory|\SampleDB.mdf;
                Integrated Security=True;
                Connect Timeout=30;
                User Instance=True";
SqlConnection Con = new SqlConnection(sqlCon);

The filepath should have |DataDirectory| which actually links to "current project directory\App_Data\" or "current project directory" and get the .mdf file.....Place the .mdf in either of these places and should work in visual studio 2010.And when you use the standalone application on production system, then the current path where the executable file is, should have the .mdf file.

Keyword not supported: "data source" initializing Entity Framework Context

The real reason you were getting this error is because of the &quot; values in your connection string.

If you replace those with single quotes then it will work fine.

https://docs.microsoft.com/archive/blogs/rickandy/explicit-connection-string-for-ef

(Posted so others can get the fix faster than I did.)

White spaces are required between publicId and systemId

Change the order of statments. For me, changing the block of code

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/beans/spring-beans.xsd" 

with

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context"

is valid.

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

Cannot read configuration file due to insufficient permissions

I have solved this by adding read permission to folder for application pool user (WIN SERVER 2008 R2): C:\Windows\System32\inetsrv\config

A little background: Our server has been hacked using classical error where app user had more permissions that it should (local admin).

To fix it we created new domain user that had only permissions on application folder, with min needed rights and assigned it as application pool user. than we hit in the issue and this was solution to our problems.

Get child Node of another Node, given node name

//xn=list of parent nodes......                
foreach (XmlNode xn in xnList)
{                                           
    foreach (XmlNode child in xn.ChildNodes) 
    {
        if (child.Name.Equals("name")) 
        {
            name = child.InnerText; 
        }
        if (child.Name.Equals("age"))
        {
            age = child.InnerText; 
        }
    }
}

Using R to list all files with a specified extension

I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:

files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]

First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.

I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Python base64 data decode

(I know this is old but I wanted to post this for people like me who stumble upon it in the future) I personally just use this python code to decode base64 strings:

print open("FILE-WITH-STRING", "rb").read().decode("base64")

So you can run it in a bash script like this:

python -c 'print open("FILE-WITH-STRING", "rb").read().decode("base64")' > outputfile
file -i outputfile

twneale has also pointed out an even simpler solution: base64 -d So you can use it like this:

cat "FILE WITH STRING" | base64 -d > OUTPUTFILE
#Or You Can Do This
echo "STRING" | base64 -d > OUTPUTFILE

That will save the decoded string to outputfile and then attempt to identify file-type using either the file tool or you can try TrID. The following command will decode the string into a file and then use TrID to automatically identify the file's type and add the extension.

echo "STRING" | base64 -d > OUTPUTFILE; trid -ce OUTPUTFILE

Map enum in JPA with fixed values?

I would do the folowing:

Declare separetly the enum, in it´s own file:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { this.value = value; }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

Declare a new JPA entity named Right

@Entity
public class Right{
    @Id
    private Integer id;
    //FIElDS

    // constructor
    public Right(RightEnum rightEnum){
          this.id = rightEnum.getValue();
    }

    public Right getInstance(RightEnum rightEnum){
          return new Right(rightEnum);
    }


}

You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)

import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 
 * 
 */
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{

    @Override //this method shoudn´t be used, but I implemented anyway, just in case
    public Integer convertToDatabaseColumn(RightEnum attribute) {
        return attribute.getValue();
    }

    @Override
    public RightEnum convertToEntityAttribute(Integer dbData) {
        return RightEnum.valueOf(dbData);
    }

}

The Authority entity:

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;

  // the **Entity** to map : 
  private Right right;

  // the **Enum** to map (not to be persisted or updated) : 
  @Column(name="COLUMN1", insertable = false, updatable = false)
  @Convert(converter = RightEnumConverter.class)
  private RightEnum rightEnum;

}

By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using

autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example

And if you need to compare, you can use:

authority.getRight().equals( RightEnum.READ ); //for example

Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.


However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).

Let´s see.

The RightEnum:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { 
            try {
                  this.value= value;
                  final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
                  field.setAccessible(true);
                  field.set(this, value);
             } catch (Exception e) {//or use more multicatch if you use JDK 1.7+
                  throw new RuntimeException(e);
            }
      }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

and the Authority entity

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;


  // the **Enum** to map (to be persisted or updated) : 
  @Column(name="COLUMN1")
  @Enumerated(EnumType.ORDINAL)
  private RightEnum rightEnum;

}

In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.

I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.

MSSQL Error 'The underlying provider failed on Open'

This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:

<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Once hosted in IIS with the same configuration, I got this error:

The underlying provider failed on Open

It was solved changing connectionString in the configuration file:

<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Other common mistakes could be:

  1. Database service could be stopped
  2. Data Source attributes pointing to a local database with Windows authentication and hosted in IIS
  3. Username and password could be wrong.

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Indeed you cannot save changes inside a foreach loop in C# using Entity Framework.

context.SaveChanges() method acts like a commit on a regular database system (RDMS).

Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges() after the loop (outside of it), like a database commit command.

This works if you can save all changes at once.

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

How to run an EXE file in PowerShell with parameters with spaces and quotes

New escape string in PowerShell V3, quoted from New V3 Language Features:

Easier Reuse of Command Lines From Cmd.exe

The web is full of command lines written for Cmd.exe. These commands lines work often enough in PowerShell, but when they include certain characters, for example, a semicolon (;), a dollar sign ($), or curly braces, you have to make some changes, probably adding some quotes. This seemed to be the source of many minor headaches.

To help address this scenario, we added a new way to “escape” the parsing of command lines. If you use a magic parameter --%, we stop our normal parsing of your command line and switch to something much simpler. We don’t match quotes. We don’t stop at semicolon. We don’t expand PowerShell variables. We do expand environment variables if you use Cmd.exe syntax (e.g. %TEMP%). Other than that, the arguments up to the end of the line (or pipe, if you are piping) are passed as is. Here is an example:

PS> echoargs.exe --% %USERNAME%,this=$something{weird}
Arg 0 is <jason,this=$something{weird}>

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

What is the best way to seed a database in Rails?

The best way is to use fixtures.

Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.

Command line tool to dump Windows DLL version?

Use Microsoft Sysinternals Sigcheck. This sample outputs just the version:

sigcheck -q -n foo.dll

Unpacked sigcheck.exe is only 228 KB.

How do I pull from a Git repository through an HTTP proxy?

There's some great answers on this already. However, I thought I would chip in as some proxy servers require you to authenticate with a user Id and password. Sometimes this can be on a domain.

So, for example if your proxy server configuration is as follows:

Server: myproxyserver
Port: 8080
Username: mydomain\myusername
Password: mypassword

Then, add to your .gitconfig file using the following command:

git config --global http.proxy http://mydomain\\myusername:mypassword@myproxyserver:8080

Don't worry about https. As long as the specified proxy server supports http, and https, then one entry in the config file will suffice.

You can then verify that the command added the entry to your .gitconfig file successfully by doing cat .gitconfig:

At the end of the file you will see an entry as follows:

[http]
    proxy = http://mydomain\\myusername:mypassword@myproxyserver:8080

That's it!

Neither BindingResult nor plain target object for bean name available as request attr

Make sure you declare the bean associated with the form in GET method of the associated controller and also add it in the model model.addAttribute("uploadItem", uploadItem); which contains @RequestMapping(method = RequestMethod.GET) annotation.

For example UploadItem.java is associated with myform.jsp and controller is SecureAreaController.java

myform.jsp contains

<form:form action="/securedArea" commandName="uploadItem" enctype="multipart/form-data"></form:form>

MyFormController.java

@RequestMapping("/securedArea")
@Controller
public class SecureAreaController {

@RequestMapping(method = RequestMethod.GET)
public String showForm(Model model) {
            UploadItem uploadItem = new UploadItem(); // declareing

            model.addAttribute("uploadItem", uploadItem); // adding in model
    return "securedArea/upload";
}

}

As you can see I am declaring UploadItem.java in controller GET method.

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

<data>
    <variable
        name="listener"
        type="my_package.MyListener" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/moreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> listener.onClick()}"
        android:text="@string/login"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}

Parsing JSON using C

Do you need to parse arbitrary JSON structures, or just data that's specific to your application. If the latter, you can make it a lot lighter and more efficient by not having to generate any hash table/map structure mapping JSON keys to values; you can instead just store the data directly into struct fields or whatever.

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

How do I check if the mouse is over an element in jQuery?

Just a note about the popular and helpful Arthur Goldsmith answer above: If you're moving your mouse from one element to another in IE (at least until IE 9) you may have some trouble getting this to work correctly if the new element has a transparent background (which it would by default). My workaround was the give the new element a transparent background image.

How to delay the .keyup() handler until the user stops typing?

Use

mytimeout = setTimeout( expression, timeout );

where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.

clearTimeout(mytimeout);

will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

Reset all the items in a form

If you have some panels or groupboxes reset fields should be recursive.

public class Utilities
{
    public static void ResetAllControls(Control form)
    {
        foreach (Control control in form.Controls)
        {
            RecursiveResetForm(control);
        }
    }

    private void RecursiveResetForm(Control control)
    {            
        if (control.HasChildren)
        {
            foreach (Control subControl in control.Controls)
            {
                RecursiveResetForm(subControl);
            }
        }
        switch (control.GetType().Name)
        {
            case "TextBox":
                TextBox textBox = (TextBox)control;
                textBox.Text = null;
                break;

            case "ComboBox":
                ComboBox comboBox = (ComboBox)control;
                if (comboBox.Items.Count > 0)
                    comboBox.SelectedIndex = 0;
                break;

            case "CheckBox":
                CheckBox checkBox = (CheckBox)control;
                checkBox.Checked = false;
                break;

            case "ListBox":
                ListBox listBox = (ListBox)control;
                listBox.ClearSelected();
                break;

            case "NumericUpDown":
                NumericUpDown numericUpDown = (NumericUpDown)control;
                numericUpDown.Value = 0;
                break;
        }
    }        
}

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

I also had the same problem and able to resolve after using below command

/root/mysql-sandboxes/3320/bin/mysqld --defaults-file=/root/mysql-sandboxes/3320/my.cnf  --user=root &

Load different application.yml in SpringBoot Test

This might be considered one of the options. now if you wanted to load a yml file ( which did not get loaded by default on applying the above annotations) the trick is to use

@ContextConfiguration(classes= {...}, initializers={ConfigFileApplicationContextInitializer.class})

Here is a sample code

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext
@ContextConfiguration(classes= {DataSourceTestConfig.class}, initializers = {ConfigFileApplicationContextInitializer.class})
public class CustomDateDeserializerTest {


    private ObjectMapper objMapper;

    @Before
    public void setUp() {
        objMapper = new ObjectMapper();

    }

    @Test
    public void test_dateDeserialization() {

    }
}

Again make sure that the setup config java file - here DataSourceTestConfig.java contains the following property values.

@Configuration
@ActiveProfiles("test")
@TestPropertySource(properties = { "spring.config.location=classpath:application-test.yml" })
public class DataSourceTestConfig implements EnvironmentAware {

    private Environment env;

    @Bean
    @Profile("test")
    public DataSource testDs() {
       HikariDataSource ds = new HikariDataSource();

        boolean isAutoCommitEnabled = env.getProperty("spring.datasource.hikari.auto-commit") != null ? Boolean.parseBoolean(env.getProperty("spring.datasource.hikari.auto-commit")):false;
        ds.setAutoCommit(isAutoCommitEnabled);
        // Connection test query is for legacy connections
        //ds.setConnectionInitSql(env.getProperty("spring.datasource.hikari.connection-test-query"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        long timeout = env.getProperty("spring.datasource.hikari.idleTimeout") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.idleTimeout")): 40000;
        ds.setIdleTimeout(timeout);
        long maxLifeTime = env.getProperty("spring.datasource.hikari.maxLifetime") != null ? Long.parseLong(env.getProperty("spring.datasource.hikari.maxLifetime")): 1800000 ;
        ds.setMaxLifetime(maxLifeTime);
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setPoolName(env.getProperty("spring.datasource.hikari.pool-name"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        int poolSize = env.getProperty("spring.datasource.hikari.maximum-pool-size") != null ? Integer.parseInt(env.getProperty("spring.datasource.hikari.maximum-pool-size")): 10;
        ds.setMaximumPoolSize(poolSize);

        return ds;
    }

    @Bean
    @Profile("test")
    public JdbcTemplate testJdbctemplate() {
        return new JdbcTemplate(testDs());
    }

    @Bean
    @Profile("test")
    public NamedParameterJdbcTemplate testNamedTemplate() {
        return new NamedParameterJdbcTemplate(testDs());
    }

    @Override
    public void setEnvironment(Environment environment) {
        // TODO Auto-generated method stub
        this.env = environment;
    }
}

CodeIgniter Active Record not equal

According to the manual this should work:

Custom key/value method:

You can include an operator in the first parameter in order to control the comparison:

$this->db->where('name !=', $name);
$this->db->where('id <', $id);
Produces: WHERE name != 'Joe' AND id < 45

Search for $this->db->where(); and look at item #2.

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

How to get a list of user accounts using the command line in MySQL?

If you are referring to the actual MySQL users, try:

select User from mysql.user;

Implement touch using Python?

If you don't mind the try-except then...

def touch_dir(folder_path):
    try:
        os.mkdir(folder_path)
    except FileExistsError:
        pass

One thing to note though, if a file exists with the same name then it won't work and will fail silently.

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

Check Ayende post on the topic: Combating the Select N + 1 Problem In NHibernate.

Basically, when using an ORM like NHibernate or EntityFramework, if you have a one-to-many (master-detail) relationship, and want to list all the details per each master record, you have to make N + 1 query calls to the database, "N" being the number of master records: 1 query to get all the master records, and N queries, one per master record, to get all the details per master record.

More database query calls ? more latency time ? decreased application/database performance.

However, ORMs have options to avoid this problem, mainly using JOINs.

Catch an exception thrown by an async void method

This blog explains your problem neatly Async Best Practices.

The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).

Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).

You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.

This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

Can promises have multiple arguments to onFulfilled?

As far as I can tell reading the ES6 Promise specification and the standard promise specification theres no clause preventing an implementation from handling this case - however its not implemented in the following libraries:

I assume the reason for them omiting multi arg resolves is to make changing order more succinct (i.e. as you can only return one value in a function it would make the control flow less intuitive) Example:

new Promise(function(resolve, reject) {
   return resolve(5, 4);
})
.then(function(x,y) {
   console.log(y);
   return x; //we can only return 1 value here so the next then will only have 1 argument
})
.then(function(x,y) {
    console.log(y);
});

Python float to int conversion

2.51 * 100 = 250.999999999997

The int() function simply truncates the number at the decimal point, giving 250. Use

int(round(2.51*100)) 

to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.

How to add parameters to HttpURLConnection using POST using NameValuePair

There's a much easier approach using PrintWriter (see here)

Basically all you need is:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();

Display A Popup Only Once Per User

*Note : This will show popup once per browser as the data is stored in browser memory.

Try HTML localStorage.

Methods :

  • localStorage.getItem('key');
  • localStorage.setItem('key','value');

$j(document).ready(function() {
    if(localStorage.getItem('popState') != 'shown'){
        $j('#popup').delay(2000).fadeIn();
        localStorage.setItem('popState','shown')
    }

    $j('#popup-close, #popup').click(function() // You are clicking the close button
    {
        $j('#popup').fadeOut(); // Now the pop up is hidden.
    });
});

Working Demo

jQuery - on change input text

Seems to me like you are updating the value of the text field in javascript. onchange event will be triggered only when you key-in data and tab out of the text field.

One workaround is to trigger the textbox change event when modifying the textbox value from the script. See below,

$("#kat").change(function(){ 
    alert("Hello");
});


$('<tab_cell>').click (function () {
   $('#kat')
      .val($(this).text()) //updating the value of the textbox 
      .change();           //trigger change event.
});

JavaScript: How to pass object by value?

As a consideration to jQuery users, there is also a way to do this in a simple way using the framework. Just another way jQuery makes our lives a little easier.

var oShallowCopy = jQuery.extend({}, o);
var oDeepCopy    = jQuery.extend(true, {}, o); 

references :

How to check permissions of a specific directory?

$ ls -ld directory

ls is the list command.

- indicates the beginning of the command options.

l asks for a long list which includes the permissions.

d indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.

How can I convert a stack trace to a string?

Code from Apache Commons Lang 3.4 (JavaDoc):

public static String getStackTrace(final Throwable throwable) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw, true);
    throwable.printStackTrace(pw);
    return sw.getBuffer().toString();
}

The difference with the other answers is that it uses autoFlush on the PrintWriter.

How do I clear all options in a dropdown box?

You can use the following to clear all the elements.

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = length-1; i >= 0; i--) {
  select.options[i] = null;
}

How to create query parameters in Javascript?

This should do the job:

const createQueryParams = params => 
      Object.keys(params)
            .map(k => `${k}=${encodeURI(params[k])}`)
            .join('&');

Example:

const params = { name : 'John', postcode: 'W1 2DL'}
const queryParams = createQueryParams(params)

Result:

name=John&postcode=W1%202DL

I want to align the text in a <td> to the top

I was facing such a problem, look at the picture below

enter image description here

and here is its HTML

<tr class="li1">
    <td valign="top">1.</td>
    <td colspan="5" valign="top">
        <p>How to build e-book learning environment</p>
    </td>
</tr>

so I fix it by changing valign Attribute in both td tags to baseline

and it worked

here is the result enter image description here

hope this help you

Inserting values to SQLite table in Android

Seems odd to be inserting a value into an automatically incrementing field.

Also, have you tried the insert() method instead of execSQL?

ContentValues insertValues = new ContentValues();
insertValues.put("Description", "Electricity");
insertValues.put("Amount", 500);
insertValues.put("Trans", 1);
insertValues.put("EntryDate", "04/06/2011");
db.insert("CashData", null, insertValues);

How do I define the name of image built with docker-compose

For docker-compose version 2 file format, you can build and tag an image for one service and then use that same built image for another service.

For my case, I want to set up an elasticsearch cluster with 2 nodes, they both need to use the same image, but configured to run differently. I also want to build my own custom elasticsearch image from my own Dockerfile. So this is what I did (docker-compose.yml):

version: '2'

services:
  es-master:
    build: ./elasticsearch
    image: porter/elasticsearch
    ports:
      - "9200:9200"
    container_name: es_master

  es-node:
    image: porter/elasticsearch
    depends_on:
      - es-master
    ports:
      - "9200"
    command: elasticsearch --discovery.zen.ping.unicast.hosts=es_master

You can see that in the first service definition es-master, I use the build option to build an image from the Dockerfile in ./elasticsearch. I tag the image with the name porter/elasticsearch with the image option.
Then, I reference this built image in the es-node service definition with the image option, and also use a depends_on to make sure the other container es-master is built and run first.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I managed to render the following SELECT with SQLAlchemy on both layers.

SELECT count(*) AS count_1
FROM "table"

Usage from the SQL Expression layer

from sqlalchemy import select, func, Integer, Table, Column, MetaData

metadata = MetaData()

table = Table("table", metadata,
              Column('primary_key', Integer),
              Column('other_column', Integer)  # just to illustrate
             )   

print select([func.count()]).select_from(table)

Usage from the ORM layer

You just subclass Query (you have probably anyway) and provide a specialized count() method, like this one.

from sqlalchemy.sql.expression import func

class BaseQuery(Query):
    def count_star(self):
        count_query = (self.statement.with_only_columns([func.count()])
                       .order_by(None))
        return self.session.execute(count_query).scalar()

Please note that order_by(None) resets the ordering of the query, which is irrelevant to the counting.

Using this method you can have a count(*) on any ORM Query, that will honor all the filter andjoin conditions already specified.

How to match letters only using java regex, matches method?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;

/* Write an application that prompts the user for a String that contains at least
 * five letters and at least five digits. Continuously re-prompt the user until a
 * valid String is entered. Display a message indicating whether the user was
 * successful or did not enter enough digits, letters, or both.
 */
public class FiveLettersAndDigits {

  private static String readIn() { // read input from stdin
    StringBuilder sb = new StringBuilder();
    int c = 0;
    try { // do not use try-with-resources. We don't want to close the stdin stream
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      while ((c = reader.read()) != 0) { // read all characters until null
        // We don't want new lines, although we must consume them.
        if (c != 13 && c != 10) {
          sb.append((char) c);
        } else {
          break; // break on new line (or else the loop won't terminate)
        }
      }
      // reader.readLine(); // get the trailing new line
    } catch (IOException ex) {
      System.err.println("Failed to read user input!");
      ex.printStackTrace(System.err);
    }

    return sb.toString().trim();
  }

  /**
   * Check the given input against a pattern
   *
   * @return the number of matches
   */
  private static int getitemCount(String input, String pattern) {
    int count = 0;

    try {
      Pattern p = Pattern.compile(pattern);
      Matcher m = p.matcher(input);
      while (m.find()) { // count the number of times the pattern matches
        count++;
      }
    } catch (PatternSyntaxException ex) {
      System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
      ex.printStackTrace(System.err);
    }

    return count;
  }

  private static String reprompt() {
    System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");

    String in = readIn();

    return in;
  }

  public static void main(String[] args) {
    int letters = 0, digits = 0;
    String in = null;
    System.out.print("Please enter five letters and five digits in any order: ");
    in = readIn();
    while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
      if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
        // count the letters and numbers. If there are enough, this loop won't happen again.
        letters = getitemCount(in, "[A-Za-z]");
        digits = getitemCount(in, "[0-9]");

        if (letters < 5 || digits < 5) {
          in = reprompt(); // reset in case we need to go around again.
        }
      } else {
        in = reprompt();
      }
    }
  }

}

phpMyAdmin mbstring error

Before sometime I also had the same problem. I have tried replacing the .dll file but no result. After some debugging I found the solution.

I had this in my php.ini file:

extension_dir = "ext"

And I'm getting mbstring extension missing error. So I tried putting the full path for the extension directory and it works for me. like:

extension_dir = "C:\php\ext"

Hope this will help.

Cheers,

python: iterate a specific range in a list

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

Materialize CSS - Select Doesn't Seem to Render

This worked for me, no jquery or select wrapper with input class, just material.js and this vanilla js:

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
});

enter image description here enter image description here

As you can tell I got the materialize css actual style and not the browsers default.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

How do you split a list into evenly sized chunks?

[AA[i:i+SS] for i in range(len(AA))[::SS]]

Where AA is array, SS is chunk size. For example:

>>> AA=range(10,21);SS=3
>>> [AA[i:i+SS] for i in range(len(AA))[::SS]]
[[10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]]
# or [range(10, 13), range(13, 16), range(16, 19), range(19, 21)] in py3

Selecting multiple items in ListView

I would advice to check the logic of ListActivity according to what is needed could be the best way not to lose much time

link

developer.android

XMLHttpRequest status 0 (responseText is empty)

To see what the problem is, when you get the cryptic error 0 go to ... | More Tools | Developer Tools (Ctrl+Shift+I) in Chrome (on the page giving the error)

Read the red text in the log to get the true error message. If there is too much in there, right-click and Clear Console, then do your last request again.

My first problem was, I was passing in Authorization headers to my own cross-domain web service for the browser for the first time.

I already had:

Access-Control-Allow-Origin: *

But not:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization

in the response header of my web service.

After I added that, my error zero was gone from my own web server, as well as when running the index.html file locally without a web server, but was still giving errors in code pen.

Back to ... | More Tools | Developer Tools while getting the error in codepen, and there is clearly explained: codepen uses https, so I cannot make calls to http, as the security is lower.

I need to therefore host my web service on https.

Knowing how to get the true error message - priceless!

move column in pandas dataframe

Simple solution:

old_cols = df.columns.values 
new_cols= ['a', 'y', 'b', 'x']
df = df.reindex(columns=new_cols)

How to push a docker image to a private repository

Ref: dock.docker.com

This topic provides basic information about deploying and configuring a registry

Run a local registry

Before you can deploy a registry, you need to install Docker on the host.

Use a command like the following to start the registry container:

start_registry.sh

#!/bin/bash

docker run -d \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  -v /data/registry:/var/lib/registry \
  registry:2

Copy an image from Docker Hub to your registry

  1. Pull the ubuntu:16.04 image from Docker Hub.

    $ docker pull ubuntu:16.04
    
  2. Tag the image as localhost:5000/my-ubuntu. This creates an additional tag for the existing image. When the first part of the tag is a hostname and port, Docker interprets this as the location of a registry, when pushing.

    $ docker tag ubuntu:16.04 localhost:5000/my-ubuntu
    
  3. Push the image to the local registry running at localhost:5000:

    $ docker push localhost:5000/my-ubuntu
    
  4. Remove the locally-cached images. This does not remove the localhost:5000/my-ubuntu image from your registry.

    $ docker image remove ubuntu:16.04
    $ docker image remove localhost:5000/my-ubuntu
    
  5. Pull the localhost:5000/my-ubuntu image from your local registry.

    $ docker pull localhost:5000/my-ubuntu
    
Deploy a plain HTTP registry

According to docs.docker.com, this is very insecure and is not recommended.

  1. Edit the daemon.json file, whose default location is /etc/docker/daemon.json on Linux or C:\ProgramData\docker\config\daemon.json on Windows Server. If you use Docker for Mac or Docker for Windows, click Docker icon -> Preferences -> Daemon, add in the insecure registry.

    If the daemon.json file does not exist, create it. Assuming there are no other settings in the file, it should have the following contents:

    {
      "insecure-registries" : ["myregistrydomain.com:5000"]
    }
    

    With insecure registries enabled, Docker goes through the following steps:

    • First, try using HTTPS.
      • If HTTPS is available but the certificate is invalid, ignore the error about the certificate.
      • If HTTPS is not available, fall back to HTTP.
  2. Restart Docker for the changes to take effect.

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

Using an HTTP PROXY - Python

I recommend you just use the requests module.

It is much easier than the built in http clients: http://docs.python-requests.org/en/latest/index.html

Sample usage:

r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Remove rows with all or some NAs (missing values) in data.frame

One approach that's both general and yields fairly-readable code is to use the filter() function and the across() helper functions from the {dplyr} package.

library(dplyr)

vars_to_check <- c("rnor", "cfam")

# Filter a specific list of columns to keep only non-missing entries

df %>% 
  filter(across(one_of(vars_to_check),
                ~ !is.na(.x)))

# Filter all the columns to exclude NA
df %>% 
  filter(across(everything(),
                ~ !is.na(.)))

# Filter only numeric columns
df %>%
  filter(across(where(is.numeric),
                ~ !is.na(.)))

Similarly, there are also the variant functions in the dplyr package (filter_all, filter_at, filter_if) which accomplish the same thing:

library(dplyr)

vars_to_check <- c("rnor", "cfam")

# Filter a specific list of columns to keep only non-missing entries
df %>% 
  filter_at(.vars = vars(one_of(vars_to_check)),
            ~ !is.na(.))

# Filter all the columns to exclude NA
df %>% 
  filter_all(~ !is.na(.))

# Filter only numeric columns
df %>%
  filter_if(is.numeric,
            ~ !is.na(.))

#1062 - Duplicate entry for key 'PRIMARY'

You need to remove shares as your PRIMARY KEY OR UNIQUE_KEY

AVD Manager - No system image installed for this target

Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.

How to extract hours and minutes from a datetime.datetime object?

If the time is 11:03, then the accepted answer will print 11:3.

You could zero-pad the minutes:

"Created at {:d}:{:02d}".format(tdate.hour, tdate.minute)

Or go another way and use tdate.time() and only take the hour/minute part:

str(tdate.time())[0:5]

How to measure height, width and distance of object using camera?

If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:

height = arctan(angle) * distance

To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is

viewportAngle = tan(ruler_length / distance)

Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches tall. (I think... it's 2am so this may be a little off)

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

When restoring a backup, how do I disconnect all active connections?

SQL Server Management Studio 2005

When you right click on a database and click Tasks and then click Detach Database, it brings up a dialog with the active connections.

Detach Screen

By clicking on the hyperlink under "Messages" you can kill the active connections.

You can then kill those connections without detaching the database.

More information here.

SQL Server Management Studio 2008

The interface has changed for SQL Server Management studio 2008, here are the steps (via: Tim Leung)

  1. Right-click the server in Object Explorer and select 'Activity Monitor'.
  2. When this opens, expand the Processes group.
  3. Now use the drop-down to filter the results by database name.
  4. Kill off the server connections by selecting the right-click 'Kill Process' option.

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

What is SaaS, PaaS and IaaS? With examples

Adding to that, I have used AWS, heroku and currently using Jelastic and found -

Jelastic offers a Java and PHP cloud hosting platform. Jelastic automatically scales Java and PHP applications and allocates server resources, thus delivering true next-generation Java and PHP cloud computing. http://blog.jelastic.com/2013/04/16/elastic-beanstalk-vs-jelastic/ or http://cloud.dzone.com/articles/jelastic-vs-heroku-1

Personally I found -

  • Jelastic is faster
  • You don’t need to code to any jelastic APIs – just upload your application and select your stack. You can also mix and match software stacks at will.

Try any of them and explore yourself. Its fun :-)

Convert pem key to ssh-rsa format

I did with

ssh-keygen -i -f $sshkeysfile >> authorized_keys

Credit goes here

MVC 4 client side validation not working

In Global.asax.cs, Application_Start() method add:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));

Debugging WebSocket in Google Chrome

Short answer for Chrome Version 29 and up:

  1. Open debugger, go to the tab "Network"
  2. Load page with websocket
  3. Click on the websocket request with upgrade response from server
  4. Select the tab "Frames" to see websocket frames
  5. Click on the websocket request again to refresh frames

How to wait for all threads to finish, using ExecutorService?

Use a CountDownLatch:

CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}

try {
  latch.await();
} catch (InterruptedException E) {
   // handle
}

and within your task (enclose in try / finally)

latch.countDown();

Cleanest way to toggle a boolean variable in Java?

If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.

public class Util {


public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }

}

then just create a Util object Util u = new Util(); and have something for the return System.out.println( u.flip(bool) );

If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Get PHP class property by string

What you're asking about is called Variable Variables. All you need to do is store your string in a variable and access it like so:

$Class = 'MyCustomClass';
$Property = 'Name';
$List = array('Name');

$Object = new $Class();

// All of these will echo the same property
echo $Object->$Property;  // Evaluates to $Object->Name
echo $Object->{$List[0]}; // Use if your variable is in an array

How to create multidimensional array

you can create array follow the code below:

var arraymultidimensional = []
    arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]];

Result:
[v1][v2] position 0
[v3][v4] position 1
[v5][v6] position 2

For add to array dinamically, use the method below:

//vectorvalue format = "[value,value,...]"
function addToArray(vectorvalue){
  arraymultidimensional[arraymultidimensional.length] = vectorvalue;
}

Hope this helps. :)

How to apply border radius in IE8 and below IE8 browsers?

PIE makes Internet Explorer 6-9 capable of rendering several of the most useful CSS3 decoration features

http://css3pie.com/

................................................................................

How to embed images in html email

You have to encode your email as multipart mime and then you can attach emails as attachments basically. You reference them by cid in the email.

Alternatively you could not attach them to the email and use URLs directly but most mail programs will block this as spammers use the trick to detect the liveness of email addresses.

You don't say what language but here is one example.

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

How to create hyperlink to call phone number on mobile devices?

I used:

Tel: <a href="tel:+123 123456789">+123 123456789</a>

and the result is:

Tel: +123 123456789

Where "Tel:" stands for pure text and only the number is coded and clickable.

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}

Counting the occurrences / frequency of array elements

How about an ECMAScript2015 option.

const a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

const aCount = new Map([...new Set(a)].map(
    x => [x, a.filter(y => y === x).length]
));
aCount.get(5)  // 3
aCount.get(2)  // 5
aCount.get(9)  // 1
aCount.get(4)  // 1

This example passes the input array to the Set constructor creating a collection of unique values. The spread syntax then expands these values into a new array so we can call map and translate this into a two-dimensional array of [value, count] pairs - i.e. the following structure:

Array [
   [5, 3],
   [2, 5],
   [9, 1],
   [4, 1]
]

The new array is then passed to the Map constructor resulting in an iterable object:

Map {
    5 => 3,
    2 => 5,
    9 => 1,
    4 => 1
}

The great thing about a Map object is that it preserves data-types - that is to say aCount.get(5) will return 3 but aCount.get("5") will return undefined. It also allows for any value / type to act as a key meaning this solution will also work with an array of objects.

_x000D_
_x000D_
function frequencies(/* {Array} */ a){_x000D_
    return new Map([...new Set(a)].map(_x000D_
        x => [x, a.filter(y => y === x).length]_x000D_
    ));_x000D_
}_x000D_
_x000D_
let foo = { value: 'foo' },_x000D_
    bar = { value: 'bar' },_x000D_
    baz = { value: 'baz' };_x000D_
_x000D_
let aNumbers = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4],_x000D_
    aObjects = [foo, bar, foo, foo, baz, bar];_x000D_
_x000D_
frequencies(aNumbers).forEach((val, key) => console.log(key + ': ' + val));_x000D_
frequencies(aObjects).forEach((val, key) => console.log(key.value + ': ' + val));
_x000D_
_x000D_
_x000D_

How do I create an executable in Visual Studio 2013 w/ C++?

Just click on "Build" on the top menu and then click on "Publish ".... Then a pop up will open and there u can define the folder which u want to save the .exe file and by clicking "Next" will allow u to set up the advanced settings... DONE!

How does internationalization work in JavaScript?

Localization support in legacy browsers is poor. Originally, this was due to phrases in the ECMAScript language spec that look like this:

Number.prototype.toLocaleString()
Produces a string value that represents the value of the Number formatted according to the conventions of the host environment’s current locale. This function is implementation-dependent, and it is permissible, but not encouraged, for it to return the same thing as toString.

Every localization method defined in the spec is defined as "implementation-dependent", which results in a lot of inconsistencies. In this instance, Chrome Opera and Safari would return the same thing as .toString(). Firefox and IE will return locale formatted strings, and IE even includes a thousand separator (perfect for currency strings). Chrome was recently updated to return a thousands-separated string, though with no fixed decimal.

For modern environments, the ECMAScript Internationalization API spec, a new standard that complements the ECMAScript Language spec, provides much better support for string comparison, number formatting, and the date and time formatting; it also fixes the corresponding functions in the Language Spec. An introduction can be found here. Implementations are available in:

  • Chrome 24
  • Firefox 29
  • Internet Explorer 11
  • Opera 15

There is also a compatibility implementation, Intl.js, which will provide the API in environments where it doesn't already exist.

Determining the user's preferred language remains a problem since there's no specification for obtaining the current language. Each browser implements a method to obtain a language string, but this could be based on the user's operating system language or just the language of the browser:

// navigator.userLanguage for IE, navigator.language for others
var lang = navigator.language || navigator.userLanguage;

A good workaround for this is to dump the Accept-Language header from the server to the client. If formatted as a JavaScript, it can be passed to the Internationalization API constructors, which will automatically pick the best (or first-supported) locale.

In short, you have to put in a lot of the work yourself, or use a framework/library, because you cannot rely on the browser to do it for you.

Various libraries and plugins for localization:

  • Others:

Feel free to add/edit.

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

Declare global variables in Visual Studio 2010 and VB.NET

There is no way to declare global variables as you're probably imagining them in VB.NET.

What you can do (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:

Public Class GlobalVariables
    Public Shared UserName As String = "Tim Johnson"
    Public Shared UserAge As Integer = 39
End Class

However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.

For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:

Public Class Form1: Inherits Form

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        MessageBox.Show("Hello, " & GlobalVariables.UserName)
    End Sub

End Class

You can't simply access the variable by typing UserName outside of the class in which it is defined—you must also specify the name of the class in which it is defined.


If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.

Imports GlobalVariables

Note that this is exactly the same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module, rather than a Class. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Module is simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.


Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everything is an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.

HTML: How to make a submit button with text + image in it?

input type="submit" is the best way to have a submit button in a form. The downside of this is that you cannot put anything other than text as its value. The button element can contain other HTML elements and content.

Try putting type="submit" instead of type="button" in your button element (source).

Pay particular attention however to the following from that page:

If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the <button> and </button> tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.

How to change position of Toast in Android?

From the documentation,

Positioning your Toast

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

For example, if you decide that the toast should appear in the top-left corner, you can set the gravity like this:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

If you want to nudge the position to the right, increase the value of the second parameter. To nudge it down, increase the value of the last parameter.

A Simple AJAX with JSP example

I have used jQuery AJAX to make AJAX requests.

Check the following code:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#call').click(function ()
            {
                $.ajax({
                    type: "post",
                    url: "testme", //this is my servlet
                    data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
                    success: function(msg){      
                            $('#output').append(msg);
                    }
                });
            });

        });
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    input:<input id="ip" type="text" name="" value="" /><br></br>
    output:<input id="op" type="text" name="" value="" /><br></br>
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    <div id="output"></div>
</body>

Generics/templates in python?

Here's a variant of this answer that uses metaclasses to avoid the messy syntax, and use the typing-style List[int] syntax:

class template(type):
    def __new__(metacls, f):
        cls = type.__new__(metacls, f.__name__, (), {
            '_f': f,
            '__qualname__': f.__qualname__,
            '__module__': f.__module__,
            '__doc__': f.__doc__
        })
        cls.__instances = {}
        return cls

    def __init__(cls, f):  # only needed in 3.5 and below
        pass

    def __getitem__(cls, item):
        if not isinstance(item, tuple):
            item = (item,)
        try:
            return cls.__instances[item]
        except KeyError:
            cls.__instances[item] = c = cls._f(*item)
            item_repr = '[' + ', '.join(repr(i) for i in item) + ']'
            c.__name__ = cls.__name__ + item_repr
            c.__qualname__ = cls.__qualname__ + item_repr
            c.__template__ = cls
            return c

    def __subclasscheck__(cls, subclass):
        for c in subclass.mro():
            if getattr(c, '__template__', None) == cls:
                return True
        return False

    def __instancecheck__(cls, instance):
        return cls.__subclasscheck__(type(instance))

    def __repr__(cls):
        import inspect
        return '<template {!r}>'.format('{}.{}[{}]'.format(
            cls.__module__, cls.__qualname__, str(inspect.signature(cls._f))[1:-1]
        ))

With this new metaclass, we can rewrite the example in the answer I link to as:

@template
def List(member_type):
    class List(list):
        def append(self, member):
            if not isinstance(member, member_type):
                raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
                    type(member).__name__,
                    type(self).__name__,
                    member_type.__name__ 
                ))

                list.append(self, member)
    return List

l = List[int]()
l.append(1)  # ok
l.append("one")  # error

This approach has some nice benefits

print(List)  # <template '__main__.List[member_type]'>
print(List[int])  # <class '__main__.List[<class 'int'>, 10]'>
assert List[int] is List[int]
assert issubclass(List[int], List)  # True

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

NPM: npm-cli.js not found when running npm

I encountered the exact same problem today in a Linux server. And the reason is really simple as I didn't do make install after make and tried to directly call the generated npm. Thus the PATH and everything was a mess.

So for me, the solution is just to do make install after make and run the npm under .node/bin/npm.

Check if key exists and iterate the JSON array using Python

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

Try it:

>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

Or, if you just want to skip over values missing ids instead of printing 'null':

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

So:

>>> getTargetIds(jsonData)
to_id: 1543

Of course in real life, you probably don't want to print each id, but to store them and do something with them, but that's another issue.

Get the size of the screen, current web page and browser window

Complete guide related to Screen sizes

JavaScript

For height:

document.body.clientHeight  // Inner height of the HTML document body, including padding 
                            // but not the horizontal scrollbar height, border, or margin

screen.height               // Device screen height (i.e. all physically visible stuff)
screen.availHeight          // Device screen height minus the operating system taskbar (if present)
window.innerHeight          // The current document's viewport height, minus taskbars, etc.
window.outerHeight          // Height the current window visibly takes up on screen 
                            // (including taskbars, menus, etc.)

Note: When the window is maximized this will equal screen.availHeight

For width:

document.body.clientWidth   // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width                // Device screen width (i.e. all physically visible stuff)
screen.availWidth           // Device screen width, minus the operating system taskbar (if present)
window.innerWidth           // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth           // The outer window width (including vertical scroll bar,
                            // toolbars, etc., includes padding and border but not margin)

Jquery

For height:

$(document).height()    // Full height of the HTML page, including content you have to 
                        // scroll to see

$(window).height()      // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.                         

For width:

$(document).width()     // The browser viewport width, minus the vertical scroll bar
$(window).width()       // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth()  // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth()  // The browser viewport width (minus the vertical scroll bar)

Reference: https://help.optimizely.com/Build_Campaigns_and_Experiments/Use_screen_measurements_to_design_for_responsive_breakpoints

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

Android: install .apk programmatically

For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
        return null;
    }
}   

To use it, in your main activity call by this way:

atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");

Execute function after Ajax call is complete

Append .done() to your ajax request.

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() { //use this
  alert("DONE!");
});

See the JQuery Doc for .done()

Xcode "Device Locked" When iPhone is unlocked

Recently I have met the Xcode shows "development cannot be enabled while your device is locked, Please unlock your device and reattach. (0xE80000E2).

If your iOS device is already unlocked and connected to mac and still get the error from Xcode 8.1 after upgrading to iOS 10.1.1, then the mac is not trusted by the device.

To fix it, first disconnect device to mac and then go to iOS settings app, and open general->reset->Reset Location & Privacy.

Then connect device to mac and when prompted, set select trust the mac.

Then wait the processing symbol files within your device and mac. After it finished, you can run the project to your device. It will be working.

How to use '-prune' option of 'find' in sh?

There are quite a few answers; some of them are a bit too much theory-heavy. I'll leave why I needed prune once so maybe the need-first/example kind of explanation is useful to someone :)

Problem

I had a folder with about 20 node directories, each having its node_modules directory as expected.

Once you get into any project, you see each ../node_modules/module. But you know how it is. Almost every module has dependencies, so what you are looking at is more like projectN/node_modules/moduleX/node_modules/moduleZ...

I didn't want to drown with a list with the dependency of the dependency of...

Knowing -d n / -depth n, it wouldn't have helped me, as the main/first node_modules directory I wanted of each project was at a different depth, like this:

Projects/MysuperProjectName/project/node_modules/...
Projects/Whatshisname/version3/project/node_modules/...
Projects/project/node_modules/...
Projects/MysuperProjectName/testProject/november2015Copy/project/node_modules/...
[...]

How can I get the first a list of paths ending at the first node_modules and move to the next project to get the same?

Enter -prune

When you add -prune, you'll still have a standard recursive search. Each "path" is analyzed, and every find gets spit out and find keeps digging down like a good chap. But it's the digging down for more node_modules what I didn't want.

So, the difference is that in any of those different paths, -prune will find to stop digging further down that particular avenue when it has found your item. In my case, the node_modules folder.

Leave only two decimal places after the dot

Using the property of String

double value = 123.456789;
String.Format("{0:0.00}", value);

Note: This can be used to display only.

Using System.Math

double value = 123.456789;
System.Math.Round(value, 2);

How do you log all events fired by an element in jQuery?

$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
     console.log(e);
}); 

"Strict Standards: Only variables should be passed by reference" error

I had a similar problem.

I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.

Let's say for example this one.

$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');

// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));

// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should 
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut 
// down the process one by one like this.

$data1  = array_keys($data);
$lastkey = array_pop($data1);

echo $lastkey;

There you go!

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Check out this solution. It worked for me..... Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app. If yes, then change the id of them and then the app runs perfectly.

I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!! Hope it works

AutoComplete TextBox Control

    private void TurnOnAutocomplete()
    {
        textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
        AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
        string[] arrayOfWowrds = new string[];

        try
        {
            //Read in data Autocomplete list to a string[]
            string[] arrayOfWowrds = new string[];
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        collection.AddRange(arrayOFWords);
        textBox.AutoCompleteCustomSource = collection;
    }

You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.

batch file - counting number of files in folder and storing in a variable

@echo off
setlocal enableextensions
set count=0
for %%x in (*.txt) do set /a count+=1
echo %count%
endlocal
pause

This is the best.... your variable is: %count%

NOTE: you can change (*.txt) to any other file extension to count other files.....

How to remove a Gitlab project?

To remove a project, you have to be the owner of this project, or the administrator of gitlab. Otherwise you can only see "rename project" but no "remove project".

NOTE THAT: the creator project is NOT always the owner of the project. If the project is in a project-group, and the project-group is created by another one, then the owner is the creator of the project-group by default.

You can find the owner's name of the project in the page Settings -> Members.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

How do I concatenate multiple C++ strings on one line?

s += "Hello world, " + "nice to see you, " + "or not.";

Those character array literals are not C++ std::strings - you need to convert them:

s += string("Hello world, ") + string("nice to see you, ") + string("or not.");

To convert ints (or any other streamable type) you can use a boost lexical_cast or provide your own function:

template <typename T>
string Str( const T & t ) {
   ostringstream os;
   os << t;
   return os.str();
}

You can now say things like:

string s = string("The meaning is ") + Str( 42 );

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

How to get build time stamp from Jenkins build variables?

You can use the Jenkins object to fetch the start time directly

Jenkins.getInstance().getItemByFullName(<your_job_name>).getBuildByNumber(<your_build_number>).getTime()

also answered it here: https://stackoverflow.com/a/63074829/1968948

Spool Command: Do not output SQL statement to file

Unfortunately SQL Developer doesn't fully honour the set echo off command that would (appear to) solve this in SQL*Plus.

The only workaround I've found for this is to save what you're doing as a script, e.g. test.sql with:

set echo off
spool c:\test.csv 
select /*csv*/ username, user_id, created from all_users;
spool off;

And then from SQL Developer, only have a call to that script:

@test.sql

And run that as a script (F5).

Saving as a script file shouldn't be much of a hardship anyway for anything other than an ad hoc query; and running that with @ instead of opening the script and running it directly is only a bit of a pain.


A bit of searching found the same solution on the SQL Developer forum, and the development team suggest it's intentional behaviour to mimic what SQL*Plus does; you need to run a script with @ there too in order to hide the query text.

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How can I render Partial views in asp.net mvc 3?

Create your partial view something like:

@model YourModelType
<div>
  <!-- HTML to render your object -->
</div>

Then in your view use:

@Html.Partial("YourPartialViewName", Model)

If you do not want a strongly typed partial view remove the @model YourModelType from the top of the partial view and it will default to a dynamic type.

Update

The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/ in the path below.

@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)

How to perform a for loop on each character in a string in Bash?

I'm surprised no one has mentioned the obvious bash solution utilizing only while and read.

while read -n1 character; do
    echo "$character"
done < <(echo -n "$words")

Note the use of echo -n to avoid the extraneous newline at the end. printf is another good option and may be more suitable for your particular needs. If you want to ignore whitespace then replace "$words" with "${words// /}".

Another option is fold. Please note however that it should never be fed into a for loop. Rather, use a while loop as follows:

while read char; do
    echo "$char"
done < <(fold -w1 <<<"$words")

The primary benefit to using the external fold command (of the coreutils package) would be brevity. You can feed it's output to another command such as xargs (part of the findutils package) as follows:

fold -w1 <<<"$words" | xargs -I% -- echo %

You'll want to replace the echo command used in the example above with the command you'd like to run against each character. Note that xargs will discard whitespace by default. You can use -d '\n' to disable that behavior.


Internationalization

I just tested fold with some of the Asian characters and realized it doesn't have Unicode support. So while it is fine for ASCII needs, it won't work for everyone. In that case there are some alternatives.

I'd probably replace fold -w1 with an awk array:

awk 'BEGIN{FS=""} {for (i=1;i<=NF;i++) print $i}'

Or the grep command mentioned in another answer:

grep -o .


Performance

FYI, I benchmarked the 3 aforementioned options. The first two were fast, nearly tying, with the fold loop slightly faster than the while loop. Unsurprisingly xargs was the slowest... 75x slower.

Here is the (abbreviated) test code:

words=$(python -c 'from string import ascii_letters as l; print(l * 100)')

testrunner(){
    for test in test_while_loop test_fold_loop test_fold_xargs test_awk_loop test_grep_loop; do
        echo "$test"
        (time for (( i=1; i<$((${1:-100} + 1)); i++ )); do "$test"; done >/dev/null) 2>&1 | sed '/^$/d'
        echo
    done
}

testrunner 100

Here are the results:

test_while_loop
real    0m5.821s
user    0m5.322s
sys     0m0.526s

test_fold_loop
real    0m6.051s
user    0m5.260s
sys     0m0.822s

test_fold_xargs
real    7m13.444s
user    0m24.531s
sys     6m44.704s

test_awk_loop
real    0m6.507s
user    0m5.858s
sys     0m0.788s

test_grep_loop
real    0m6.179s
user    0m5.409s
sys     0m0.921s

How to insert a value that contains an apostrophe (single quote)?

Escape the apostrophe (i.e. double-up the single quote character) in your SQL:

INSERT INTO Person
    (First, Last)
VALUES
    ('Joe', 'O''Brien')
              /\
          right here  

The same applies to SELECT queries:

SELECT First, Last FROM Person WHERE Last = 'O''Brien'

The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote. (Two single quote characters, not double-quote instead of a single quote.)

Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

How to call stopservice() method of Service class from the calling activity class

That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.

If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.

AutoService

class AutoService extends IntentService {
     private static final String TAG = "AutoService";
     private Timer timer;    
     private TimerTask task;

     public onCreate() {
          timer = new Timer();
          timer = new TimerTask() {
            public void run() 
            {
                System.out.println("done");
            }
          }
     }

     protected void onHandleIntent(Intent i) {
        Log.d(TAG, "onHandleIntent");     

        int delay = 5000; // delay for 5 sec.
        int period = 5000; // repeat every sec.


        timer.scheduleAtFixedRate(timerTask, delay, period);
     }

     public boolean stopService(Intent name) {
        // TODO Auto-generated method stub
        timer.cancel();
        task.cancel();
        return super.stopService(name);
    }

}

Combining CSS Pseudo-elements, ":after" the ":last-child"

This works :) (I hope multi-browser, Firefox likes it)

_x000D_
_x000D_
li { display: inline; list-style-type: none; }_x000D_
li:after { content: ", "; }_x000D_
li:last-child:before { content: "and "; }_x000D_
li:last-child:after { content: "."; }
_x000D_
<html>_x000D_
  <body>_x000D_
    <ul>_x000D_
      <li>One</li>_x000D_
      <li>Two</li>_x000D_
      <li>Three</li>_x000D_
    </ul>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

In the shell, what does " 2>&1 " mean?

2>&1 is a POSIX shell construct. Here is a breakdown, token by token:


2: "Standard error" output file descriptor.

>&: Duplicate an Output File Descriptor operator (a variant of Output Redirection operator >). Given [x]>&[y], the file descriptor denoted by x is made to be a copy of the output file descriptor y.

1 "Standard output" output file descriptor.

The expression 2>&1 copies file descriptor 1 to location 2, so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").


Further explanation:

File Descriptor: "A per-process unique, non-negative integer used to identify an open file for the purpose of file access."

Standard output/error: Refer to the following note in the Redirection section of the shell documentation:

Open files are represented by decimal numbers starting with zero. The largest possible value is implementation-defined; however, all implementations shall support at least 0 to 9, inclusive, for use by the application. These numbers are called "file descriptors". The values 0, 1, and 2 have special meaning and conventional uses and are implied by certain redirection operations; they are referred to as standard input, standard output, and standard error, respectively. Programs usually take their input from standard input, and write output on standard output. Error messages are usually written on standard error. The redirection operators can be preceded by one or more digits (with no intervening characters allowed) to designate the file descriptor number.

How do I delete from multiple tables using INNER JOIN in SQL server

DELETE     TABLE1 LIN
FROM TABLE1 LIN
INNER JOIN TABLE2 LCS ON  CONDITION
WHERE CONDITION

Inconsistent Accessibility: Parameter type is less accessible than method

The problem doesn't seem to be with the variable but rather with the declaration of ACTInterface. Is ACTInterface declared as internal by any chance?

Output data from all columns in a dataframe in pandas

Use:

pandas.set_option('display.max_columns', 7)

This will force Pandas to display the 7 columns you have. Or more generally:

pandas.set_option('display.max_columns', None)

which will force it to display any number of columns.

Explanation: the default for max_columns is 0, which tells Pandas to display the table only if all the columns can be squeezed into the width of your console.

Alternatively, you can change the console width (in chars) from the default of 80 using e.g:

pandas.set_option('display.width', 200)

What is the equivalent to getch() & getche() in Linux?

There is a getch() function in the ncurses library. You can get it by installing the ncurses-dev package.

Android - How to regenerate R class?

Try to add a new "Android XML file" to, for example, the /res/layout folder. This might cause the plugin to to regenerate the R class.

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

Building up on Paul Burke's answer I faced many problems resolving external SD card's URI path as most of the suggested "built-in" functions return paths which do not get resolved to files.

However, this is my approach of his // TODO handle non-primary volumes.

String resolvedPath = "";
File[] possibleExtSdComposites = context.getExternalFilesDirs(null);
for (File f : possibleExtSdComposites) {
    // Reset final path
    resolvedPath = "";

    // Construct list of folders
    ArrayList<String> extSdSplit = new ArrayList<>(Arrays.asList(f.getPath().split("/")));

    // Look for folder "<your_application_id>"
    int idx = extSdSplit.indexOf(BuildConfig.APPLICATION_ID);

    // ASSUMPTION: Expected to be found at depth 2 (in this case ExtSdCard's root is /storage/0000-0000/) - e.g. /storage/0000-0000/Android/data/<your_application_id>/files
    ArrayList<String> hierarchyList = new ArrayList<>(extSdSplit.subList(0, idx - 2));

    // Construct list containing full possible path to the file
    hierarchyList.add(tail);
    String possibleFilePath = TextUtils.join("/", hierarchyList);

    // If file is found --> success
    if (idx != -1 && new File(possibleFilePath).exists()) {
        resolvedPath = possibleFilePath;
        break;
    }
}

if (!resolvedPath.equals("")) {
    return resolvedPath;
} else {
    return null;
}

Note it depends on hierarchy which might be different on every phone manufacturer - I have not tested them all (it worked well so far on Xperia Z3 API 23 and Samsung Galaxy A3 API 23).

Please confirm if it does not perform well elsewhere.

Add button to navigationbar programmatically

Inside my UIViewController derived class, I am using the following inside viewDidLoad:

UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Flip"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];

This adds a button to the right hand side with the title Flip, which calls the method:

-(IBAction)flipView

This looks very much like you #3, but it is working within my code.

What does body-parser do with express?

If you don't want to use seperate npm package body-parser, latest express (4.16+) has built-in body-parser middleware and can be used like this,

const app = express();
app.use(express.json({ limit: '100mb' }));

p.s. Not all functionalities of body parse are present in the express. Refer documentation for full usage here

Specifying trust store information in spring boot application.properties

Although I am commenting late. But I have used this method to do the job. Here when I am running my spring application I am providing the application yaml file via -Dspring.config.location=file:/location-to-file/config-server-vault-application.yml which contains all of my properties

config-server-vault-application.yml
***********************************
server:
  port: 8888
  ssl:
    trust-store: /trust-store/config-server-trust-store.jks
    trust-store-password: config-server
    trust-store-type: pkcs12

************************************
Java Code
************************************
@SpringBootApplication
public class ConfigServerApplication {

 public static void main(String[] args) throws IOException {
    setUpTrustStoreForApplication();
    SpringApplication.run(ConfigServerApplication.class, args);
 }

 private static void setUpTrustStoreForApplication() throws IOException {
    YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    List<PropertySource<?>> applicationYamlPropertySource = loader.load(
            "config-application-properties", new UrlResource(System.getProperty("spring.config.location")));
    Map<String, Object> source = ((MapPropertySource) applicationYamlPropertySource.get(0)).getSource();
    System.setProperty("javax.net.ssl.trustStore", source.get("server.ssl.trust-store").toString());
    System.setProperty("javax.net.ssl.trustStorePassword", source.get("server.ssl.trust-store-password").toString());
  }
}

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

how to get the host url using javascript from the current page

This should work:

window.location.hostname

Tools to generate database tables diagram with Postgresql?

Inside Eclipse I've used the Clay plugin (ex Clay-Azurri). The free version allows to introspect ("reverse engineer") an existing DB schema (via JDBC) and make a diagram of some selected tables.

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How to make a Python script run like a service or daemon in Linux

You have two options here.

  1. Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.

  2. Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).

I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.

Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.

selected value get from db into dropdown select box option using php mysql error

BEST code and simple

<select id="example-getting-started" multiple="multiple" name="category">

    <?php
    $query = "select * from mine";
    $results = mysql_query($query);

    while ($rows = mysql_fetch_assoc(@$results)){ 
    ?>
    <option value="<?php echo $rows['category'];?>"><?php echo $rows['category'];?></option>

    <?php
    } 
    ?>
</select>

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

Method List in Visual Studio Code

For PHP users :)

  1. Make sure you have 'PHP Symbol' plugin then you can get all methods and class in 'OUTLINE' Sidebar's Bottom.

  2. Press ? command + ? shift + O in "macOS" or Ctrl + Shift + O while using "Windows"

OUTLINE: enter image description here

@Symbol: enter image description here

How to flush output after each `echo` call?

Flushing seemingly failing to work is a side effect of automatic character set detection.

The browser will not display anything until it knows the character set to display it in, and if you don't specify the character set, it need tries to guess it. The problem being that it can't make a good guess without enough data, which is why browsers seem to have this 1024 byte (or similar) buffer they need filled before displaying anything.

The solution is therefore to make sure the browser doesn't have to guess the character set.

If you're sending text, add a '; charset=utf-8' to its content type, and if it's HTML, add the character set to the appropriate meta tag.

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

getFilesDir() vs Environment.getDataDirectory()

getFilesDir()

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

Environment.getDataDirectory()

Return the user data directory.

Regex to match string containing two names in any order

You can make use of regex's quantifier feature since lookaround may not be supported all the time.

(\bjames\b){1,}.*(\bjack\b){1,}|(\bjack\b){1,}.*(\bjames\b){1,}

Upper memory limit?

Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about

1959167 [MiB]

On jython 2.5 it crashes earlier:

 239000 [MiB]

probably I can configure Jython to use more memory (it uses limits from JVM)

Test app:

import sys

sl = []
i = 0
# some magic 1024 - overhead of string object
fill_size = 1024
if sys.version.startswith('2.7'):
    fill_size = 1003
if sys.version.startswith('3'):
    fill_size = 497
print(fill_size)
MiB = 0
while True:
    s = str(i).zfill(fill_size)
    sl.append(s)
    if i == 0:
        try:
            sys.stderr.write('size of one string %d\n' % (sys.getsizeof(s)))
        except AttributeError:
            pass
    i += 1
    if i % 1024 == 0:
        MiB += 1
        if MiB % 25 == 0:
            sys.stderr.write('%d [MiB]\n' % (MiB))

In your app you read whole file at once. For such big files you should read the line by line.

How to display a json array in table format?

DEMO

var obj=[
        {
            id : "001",
            name : "apple",
            category : "fruit",
            color : "red"
        },
        {
            id : "002",
            name : "melon",
            category : "fruit",
            color : "green"
        },
        {
            id : "003",
            name : "banana",
            category : "fruit",
            color : "yellow"
        }
    ]
    var tbl=$("<table/>").attr("id","mytable");
    $("#div1").append(tbl);
    for(var i=0;i<obj.length;i++)
    {
        var tr="<tr>";
        var td1="<td>"+obj[i]["id"]+"</td>";
        var td2="<td>"+obj[i]["name"]+"</td>";
        var td3="<td>"+obj[i]["color"]+"</td></tr>";

       $("#mytable").append(tr+td1+td2+td3); 

    }   

In Python script, how do I set PYTHONPATH?

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

sys.path.append('/path/to/whatever')

In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Extreme wait-time when taking a SQL Server database offline

After some additional searching (new search terms inspired by gbn's answer and u07ch's comment on KMike's answer) I found this, which completed successfully in 2 seconds:

ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE

(Update)

When this still fails with the following error, you can fix it as inspired by this blog post:

ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.

you can run the following command to find out who is keeping a lock on your database:

EXEC sp_who2

And use whatever SPID you find in the following command:

KILL <SPID>

Then run the ALTER DATABASE command again. It should now work.

npm start error with create-react-app

Add .env file with "SKIP_PREFLIGHT_CHECK=true" than npm start

How to compile and run C in sublime text 3?

If you code C or C++ language. I think we are lucky because we could use a file to input. It is so convenient and clear. I often do that. This is argument to implement it :

{
freopen("inputfile", "r", stdin);
}

Notice that inputfile must locate at same directory with source code file, r is stand for read.

How to make primary key as autoincrement for Room Persistence lib

Annotate your Entity class with the code below.

In Java:

@PrimaryKey(autoGenerate = true)
private int id;

In Kotlin:

@PrimaryKey(autoGenerate = true)
var id: Int

Room will then auto-generate and auto-increment the id field.

How to map to multiple elements with Java 8 streams?

To do this, I had to come up with an intermediate data structure:

class KeyDataPoint {
    String key;
    DateTime timestamp;
    Number data;
    // obvious constructor and getters
}

With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.

Then, we apply a groupingBy operation on the string key in order to gather the data for each key together. Note that a simple groupingBy would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy which is a mapping operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping operation is simply toList which collects the DataPoint objects of the same group into a list.

Now we have a Map<String, List<DataPoint>> and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.

The code ends up looking like this:

Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.getData().entrySet().stream()
                           .map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
        .collect(groupingBy(KeyDataPoint::getKey,
                    mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

I took some liberties with constructors and getters, but I think they should be obvious.

Fail during installation of Pillow (Python module) in Linux

The alternative, if you don't want to install libjpeg:

CFLAGS="--disable-jpeg" pip install pillow

From https://pillow.readthedocs.io/en/3.0.0/installation.html#external-libraries

What is the "realm" in basic authentication

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

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

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

VBA Excel Provide current Date in Text box

Here's a more simple version. In the cell you want the date to show up just type

=Today()      

Format the cell to the date format you want and Bob's your uncle. :)

React: how to update state.item[1] in state using setState?

Try this it will definetly work,other case i tried but didn't work

import _ from 'lodash';

this.state.var_name  = _.assign(this.state.var_name, {
   obj_prop: 'changed_value',
});

How to do while loops with multiple conditions

while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.

How to search text using php if ($text contains "World")

in my opinion strstr() is better than strpos(). because strstr() is compatible with both PHP 4 AND PHP 5. but strpos() is only compatible with PHP 5. please note that part of servers have no PHP 5

Running Node.js in apache?

While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.

In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.

Perform Segue programmatically and pass parameters to the destination view

I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.

I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.

Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.

1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.

Overriding fields or properties in subclasses

The example implementation when you want to have an abstract class with implementation. Subclasses must:

  1. Parameterize the implementation of an abstract class.
  2. Fully inherit the implementation of the abstract class;
  3. Have your own implementation.

In this case, the properties that are necessary for the implementation should not be available for use except for the abstract class and its own subclass.

    internal abstract class AbstractClass
    {
        //Properties for parameterization from concrete class
        protected abstract string Param1 { get; }
        protected abstract string Param2 { get; }

        //Internal fields need for manage state of object
        private string var1;
        private string var2;

        internal AbstractClass(string _var1, string _var2)
        {
            this.var1 = _var1;
            this.var2 = _var2;
        }

        internal void CalcResult()
        {
            //The result calculation uses Param1, Param2, var1, var2;
        }
    }

    internal class ConcreteClassFirst : AbstractClass
    {
        private string param1;
        private string param2;
        protected override string Param1 { get { return param1; } }
        protected override string Param2 { get { return param2; } }

        public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
        {
            //The calculation param1 and param2
        }
    }

    internal class ConcreteClassSecond : AbstractClass
    {
        private string param1;
        private string param2;

        protected override string Param1 { get { return param1; } }

        protected override string Param2 { get { return param2; } }

        public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }

        internal void CalcParams()
        {
            //The calculation param1 and param2
        }
    }

    static void Main(string[] args)
    {
        string var1_1 = "val1_1";
        string var1_2 = "val1_2";

        ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);
        concreteClassFirst.CalcParams();
        concreteClassFirst.CalcResult();

        string var2_1 = "val2_1";
        string var2_2 = "val2_2";

        ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);
        concreteClassSecond.CalcParams();
        concreteClassSecond.CalcResult();

        //Param1 and Param2 are not visible in main method
    }

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

How to justify a single flexbox item (override justify-content)

If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.

_x000D_
_x000D_
.space-between {_x000D_
  border: 1px solid red;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
  border: 1px solid blue;_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
  <div class="child">1</div>_x000D_
  <div class="default-flex">_x000D_
    <div class="child">2</div>_x000D_
    <div class="child">3</div>_x000D_
    <div class="child">4</div>_x000D_
    <div class="child">5</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.

Two Divs on the same row and center align both of them

Could this do for you? Check my JSFiddle

And the code:

HTML

<div class="container">
    <div class="div1">Div 1</div>
    <div class="div2">Div 2</div>
</div>

CSS

div.container {
    background-color: #FF0000;
    margin: auto;   
    width: 304px;
}

div.div1 {
    border: 1px solid #000;
    float: left;
    width: 150px;
}

div.div2 {
    border: 1px solid red;
    float: left;
    width: 150px;
}

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

Twitter bootstrap progress bar animation on page load

In contribution to ellabeauty's answer. you can also use this dynamic percentage values

$('.bar').css('width',  function(){ return ($(this).attr('data-percentage')+'%')});

And probably add custom easing to your css

.bar {
 -webkit-transition: width 2.50s ease !important;
 -moz-transition: width 2.50s ease !important;
   -o-transition: width 2.50s ease !important;
      transition: width 2.50s ease !important;
 }

How do I Merge two Arrays in VBA?

I tried the code provided above, but it gave an error 9 for me. I made this code, and it worked fine for my purposes. I hope others find it useful as well.

Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant

    Dim returnThis() As Variant
    Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
    len1 = UBound(arr1)
    len2 = UBound(arr2)
    lenRe = len1 + len2
    ReDim returnThis(1 To lenRe)
    counter = 1

    Do While counter <= len1 'get first array in returnThis
        returnThis(counter) = arr1(counter)
        counter = counter + 1
    Loop
    Do While counter <= lenRe 'get the second array in returnThis
        returnThis(counter) = arr2(counter - len1)
        counter = counter + 1
    Loop

mergeArrays = returnThis
End Function

How to update Ruby to 1.9.x on Mac?

There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.

I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

Refused to apply inline style because it violates the following Content Security Policy directive

As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none) in your HTML. Put that style in your CSS file instead.

To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:

"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."

Linux Process States

While waiting for read() or write() to/from a file descriptor return, the process will be put in a special kind of sleep, known as "D" or "Disk Sleep". This is special, because the process can not be killed or interrupted while in such a state. A process waiting for a return from ioctl() would also be put to sleep in this manner.

An exception to this is when a file (such as a terminal or other character device) is opened in O_NONBLOCK mode, passed when its assumed that a device (such as a modem) will need time to initialize. However, you indicated block devices in your question. Also, I have never tried an ioctl() that is likely to block on a fd opened in non blocking mode (at least not knowingly).

How another process is chosen depends entirely on the scheduler you are using, as well as what other processes might have done to modify their weights within that scheduler.

Some user space programs under certain circumstances have been known to remain in this state forever, until rebooted. These are typically grouped in with other "zombies", but the term would not be correct as they are not technically defunct.

C++ Redefinition Header Files (winsock2.h)

#include guards are the standard way of doing this. #pragma once is not, meaning that not all compilers support it.

HTML inside Twitter Bootstrap popover

Add this to the bottom of your popper.js file:

Popper.Defaults.modifiers.computeStyle.gpuAcceleration = !(window.devicePixelRatio < 1.5 && /Win/.test(navigator.platform));

Source: https://github.com/twbs/bootstrap/issues/23590

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

Connect to Oracle DB using sqlplus

sqlplus username/password@database

Eg:

sqlplus hr/hr@orcl

How can I grep for a string that begins with a dash/hyphen?

ls -l | grep "^-"

Hope this one would serve your purpose.

How do I convert datetime to ISO 8601 in PHP

After PHP 5 you can use this: echo date("c"); form ISO 8601 formatted datetime.

http://ideone.com/nD7piL

Note for comments:

Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh].

But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c"). A similar discussion here.

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

Measure execution time for a Java method

In case you develop applications for Android you should try out the TimingLogger class.
Take a look at these articles describing the usage of the TimingLogger helper class:

How do I create dynamic properties in C#?

I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.

Implementing ICustomTypeDescriptor for dynamic properties:

I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.

This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.

By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.

Take a look at the implementation of the data 'row' class below:

/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Gets the Attributes for the object
    /// </summary>
    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
        return new AttributeCollection(null);
    }

    /// <summary>
    /// Gets the Class name
    /// </summary>
    string ICustomTypeDescriptor.GetClassName()
    {
        return null;
    }

    /// <summary>
    /// Gets the component Name
    /// </summary>
    string ICustomTypeDescriptor.GetComponentName()
    {
        return null;
    }

    /// <summary>
    /// Gets the Type Converter
    /// </summary>
    TypeConverter ICustomTypeDescriptor.GetConverter()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Event
    /// </summary>
    /// <returns></returns>
    EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Property
    /// </summary>
    PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
    {
        return null;
    }

    /// <summary>
    /// Gets the Editor
    /// </summary>
    object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
    {
        return null;
    }

    /// <summary>
    /// Gets the Events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
    {
        List<propertydescriptor> properties = new List<propertydescriptor>();

        //Add property descriptors for each entry in the dictionary
        foreach (string key in this.Keys)
        {
            properties.Add(new TestResultPropertyDescriptor(key));
        }

        //Get properties also belonging to this class also
        PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);

        foreach (PropertyDescriptor oPropertyDescriptor in pdc)
        {
            properties.Add(oPropertyDescriptor);
        }

        return new PropertyDescriptorCollection(properties.ToArray());
    }

    /// <summary>
    /// gets the Properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
    {
        return ((ICustomTypeDescriptor)this).GetProperties(null);
    }

    /// <summary>
    /// Gets the property owner
    /// </summary>
    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}

Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt

You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:

/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
    //- PROPERTIES --------------------------------------------------------------------------------------------------------------

    #region Properties

    /// <summary>
    /// Component Type
    /// </summary>
    public override Type ComponentType
    {
        get { return typeof(Dictionary<string, TestResultValue>); }
    }

    /// <summary>
    /// Gets whether its read only
    /// </summary>
    public override bool IsReadOnly
    {
        get { return false; }
    }

    /// <summary>
    /// Gets the Property Type
    /// </summary>
    public override Type PropertyType
    {
        get { return typeof(string); }
    }

    #endregion Properties

    //- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------

    #region Constructor

    /// <summary>
    /// Constructor
    /// </summary>
    public TestResultPropertyDescriptor(string key)
        : base(key, null)
    {

    }

    #endregion Constructor

    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Can Reset Value
    /// </summary>
    public override bool CanResetValue(object component)
    {
        return true;
    }

    /// <summary>
    /// Gets the Value
    /// </summary>
    public override object GetValue(object component)
    {
          return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
    }

    /// <summary>
    /// Resets the Value
    /// </summary>
    public override void ResetValue(object component)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
    }

    /// <summary>
    /// Sets the value
    /// </summary>
    public override void SetValue(object component, object value)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
    }

    /// <summary>
    /// Gets whether the value should be serialized
    /// </summary>
    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}

The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.

Taken from my blog at:

ICustomTypeDescriptor Implementation for dynamic properties

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

MacPorts is another package manager for OS X:.

Installation instructions are at The MacPorts Project -- Download & Installation after which one issues sudo port install pythonXX, where XX is 27 or 35.

Posting parameters to a url using the POST method without using a form

cURL is an option, using Ajax as well eventhough solving back-end problems with the front-end isn't so neat.

A very useful post about doing it without cURL is this one: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl

The code to do this (untested, unimproved, from the blog post):

function do_post_request($url, $data, $optional_headers = null)
{
   $params = array('http' => array(
                'method' => 'POST',
                'content' => $data
             ));
   if ($optional_headers !== null) {
      $params['http']['header'] = $optional_headers;
   }
   $ctx = stream_context_create($params);
   $fp = @fopen($url, 'rb', false, $ctx);
   if (!$fp) {
      throw new Exception("Problem with $url, $php_errormsg");
   }
   $response = @stream_get_contents($fp);
   if ($response === false) {
      throw new Exception("Problem reading data from $url, $php_errormsg");
   }
   return $response;
}

Why is enum class preferred over plain enum?

Because, as said in other answers, class enum are not implicitly convertible to int/bool, it also helps to avoid buggy code like:

enum MyEnum {
  Value1,
  Value2,
};
...
if (var == Value1 || Value2) // Should be "var == Value2" no error/warning

Difference between Big-O and Little-O Notation

The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than another. To say that one function is asymptotically less than another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).

How to pass 2D array (matrix) in a function in C?

2D array:

int sum(int array[][COLS], int rows)
{

}

3D array:

int sum(int array[][B][C], int A)
{

}

4D array:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

How can you encode a string to Base64 in JavaScript?

Contributing with a minified polyfill for window.atob + window.btoa that I'm currently using.

(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();

Set up a scheduled job?

I use celery to create my periodical tasks. First you need to install it as follows:

pip install django-celery

Don't forget to register django-celery in your settings and then you could do something like this:

from celery import task
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from celery.utils.log import get_task_logger
@periodic_task(run_every=crontab(minute="0", hour="23"))
def do_every_midnight():
 #your code

The meaning of NoInitialContextException error

Is a JNDI problem. You will see that exception if the InitialContext class has neither default properties for the JNDI service provider nor explicitly configured server properties.

Set the Context.INITIAL_CONTEXT_FACTORY environment property to the class name of the initial context implementation that you are using. This class must be available to your program in the classpath.

Check:

Set inputType for an EditText Programmatically?

password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);

also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.

What is the "-->" operator in C/C++?

Anyway, we have a "goes to" operator now. "-->" is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.

Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)" on some platforms.

Producing a new line in XSLT

You can use: <xsl:text>&#10;</xsl:text>

see the example

<xsl:variable name="module-info">
  <xsl:value-of select="@name" /> = <xsl:value-of select="@rev" />
  <xsl:text>&#10;</xsl:text>
</xsl:variable>

if you write this in file e.g.

<redirect:write file="temp.prop" append="true">
  <xsl:value-of select="$module-info" />
</redirect:write>

this variable will produce a new line infile as:

commons-dbcp_commons-dbcp = 1.2.2
junit_junit = 4.4
org.easymock_easymock = 2.4

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

Problem

I had a similar problem using axes. The class parameter is frameon but the kwarg is frame_on. axes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

Solution

frame_on

Example

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

How does one remove a Docker image?

For me the following worked fine:

> docker images
REPOSITORY   TAG           IMAGE ID          CREATED             SIZE
debian       jessie        86baf4e8cde9      3 weeks ago         123MB
ubuntu       yakkety       7d3f705d307c      3 weeks ago         107MB
alpine       3.5           074d602a59d7      7 weeks ago         3.99MB

Then go ahead and remove an image by running some like these:

> docker rmi debian:jessie
> docker rmi ubuntu:yakkety
> docker rmi alipine:3.5

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

here-document gives 'unexpected end of file' error

When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.

See how I define USAGE for a solution that:

  • auto-formats well for me in my IDE of choice (sublime)
  • is multi-line
  • can use spaces or tabs as indentation
  • preserves indentations within the comment.
function foo {
    # Docstring
    read -r -d '' USAGE <<'    END'
        # This method prints foo to the terminal.
        #
        # Enter `foo -h` to see the docstring.
        #      It has indentations and multiple lines.
        #
        # Change the delimiter if you need hashtag for some reason.
        # This can include $$ and = and eval, but won't be evaluated
    END


    if [ "$1" = "-h" ]
    then
        echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-
        return
    fi

    echo "foo"
}

So foo -h yields:

This method prints foo to the terminal.

Enter `foo -h` to see the docstring.
     It has indentations and multiple lines.

Change the delimiter if you need hashtag for some reason.
This can include $$ and = and eval, but won't be evaluated

Explanation

cut -d "#" -f 2: Retrieve the second portion of the # delimited lines. (Think a csv with "#" as the delimiter, empty first column).

cut -c 2-: Retrieve the 2nd to end character of the resultant string

Also note that if [ "$1" = "-h" ] evaluates as False if there is no first argument, w/o error, since it becomes an empty string.

Variable interpolation in the shell

In Bash:

tail -1 ${filepath}_newstap.sh

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">
</div></div>

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

How to programmatically set drawableLeft on Android button?

Kotlin Version

Use below snippet to add a drawable left to the button:

val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)

.

Important Point in Using Android Vector Drawable

When you are using an android vector drawable and want to have backward compatibility for API below 21, add the following codes to:

In app level build.gradle:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

In Application class:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }

}

Algorithm to find Largest prime factor of a number

Python Iterative approach by removing all prime factors from the number

def primef(n):
    if n <= 3:
        return n
    if n % 2 == 0:
        return primef(n/2)
    elif n % 3 ==0:
        return primef(n/3)
    else:
        for i in range(5, int((n)**0.5) + 1, 6):
            #print i
            if n % i == 0:
                return primef(n/i)
            if n % (i + 2) == 0:
                return primef(n/(i+2))
    return n

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

C++ Best way to get integer division and remainder

Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).

Take it with a grain of salt:

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    div_t result;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        result = div(i,3);
        doNothing(result.quot,result.rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 150

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    int dividend;
    int rem;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        dividend = i / 3;
        rem = i % 3;
        doNothing(dividend,rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 25

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );