Programs & Examples On #Contactscontract

Android's Contacts API is defined in the android.provider.ContactsContract and related classes.

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

After doing some research, it seems that this problem may be due to a google bug. For me, I was able to leave this line in my Activities onCreate method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

AND I changed my targetSdkVersion to 26. Having that line in my onCreate still resulted in a crash while my targetSdkVersion was still set at 27. Since no one else's solution has worked for me thus far, I found that this works as a temporary fix for now.

Send text to specific contact programmatically (whatsapp)

It lets you open WhatsApp conversation screen for that specific user you are trying to communicate with:

private void openWhatsApp() {
    String smsNumber = "91XXXXXXXX20";
    boolean isWhatsappInstalled = whatsappInstalledOrNot("com.whatsapp");
    if (isWhatsappInstalled) {

        Intent sendIntent = new Intent("android.intent.action.MAIN");
        sendIntent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
        sendIntent.putExtra("jid", PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net");//phone number without "+" prefix

        startActivity(sendIntent);
    } else {
        Uri uri = Uri.parse("market://details?id=com.whatsapp");
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        Toast.makeText(this, "WhatsApp not Installed",
                Toast.LENGTH_SHORT).show();
        startActivity(goToMarket);
    }
}

private boolean whatsappInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

How to add new contacts in android

Here I am posting a piece of code that i use to add a new contact. It works fine for me. I hope it will help you.

 String DisplayName = "XYZ";
 String MobileNumber = "123456";
 String HomeNumber = "1111";
 String WorkNumber = "2222";
 String emailID = "[email protected]";
 String company = "bad";
 String jobTitle = "abcd";

 ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();

 ops.add(ContentProviderOperation.newInsert(
 ContactsContract.RawContacts.CONTENT_URI)
     .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
     .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
     .build());

 //------------------------------------------------------ Names
 if (DisplayName != null) {
     ops.add(ContentProviderOperation.newInsert(
     ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
         .withValue(
     ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
     DisplayName).build());
 }

 //------------------------------------------------------ Mobile Number                     
 if (MobileNumber != null) {
     ops.add(ContentProviderOperation.
     newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
         .build());
 }

 //------------------------------------------------------ Home Numbers
 if (HomeNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
         .build());
 }

 //------------------------------------------------------ Work Numbers
 if (WorkNumber != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
         .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
     ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Email
 if (emailID != null) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
         .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
         .build());
 }

 //------------------------------------------------------ Organization
 if (!company.equals("") && !jobTitle.equals("")) {
     ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
         .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
         .withValue(ContactsContract.Data.MIMETYPE,
     ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
         .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
         .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
         .build());
 }

 // Asking the Contact provider to create a new contact                 
 try {
     getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
 } catch (Exception e) {
     e.printStackTrace();
     Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
 } 

Here is the code. Integrate it according to your need. I hope it will help.

How to add new elements to an array?

String[] source = new String[] { "a", "b", "c", "d" };
String[] destination = new String[source.length + 2];
destination[0] = "/bin/sh";
destination[1] = "-c";
System.arraycopy(source, 0, destination, 2, source.length);

for (String parts : destination) {
  System.out.println(parts);
}

Laravel: PDOException: could not find driver

if you have installed new version of php 7.2+ then you have to uncomment this line in php.ini ;extension=pdo_mysql

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

How to find files modified in last x minutes (find -mmin does not work as expected)

Manual of find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

   -amin n
          File was last accessed n minutes ago.

   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.

   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.

   -cmin n
          File's status was last changed n minutes ago.

   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.

   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time

Difference between `Optional.orElse()` and `Optional.orElseGet()`

First of all check the declaration of both the methods.

1) OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

2) OrElseGet: Execute logic if value inside the optional is null

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.

Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.

Optional.of(getModel())
   .map(x -> {
      //some logic
   })
  .orElse(getDefaultAndLogError());

getDefaultAndLogError() {
  log.error("No Data found, Returning default");
  return defaultValue;
}

Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.

Optional.of(getModel())
   .map(x -> //some logic)
   .orElse(getDefaultFromDb());

getDefaultFromDb() {
   return dataBaseServe.getDefaultValue(); //api call, db call.
}

Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.

List<Model> list = new ArrayList<>();
Optional.of(getModel())
  .map(x -> {
  })
  .orElse(get(list));

get(List < String > list) {
   log.error("No Data found, Returning default");
   list.add(defaultValue);
   return defaultValue;
}

Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.

Key takeaways from this:

  1. Do not use “Optional.orElse” if it contains any log statement.
  2. Do not use “Optional.orElse” if it contains time-intensive logic.
  3. Do not use “Optional.orElse” if it is mutating some object state.
  4. Use “Optional.orElse” if we have to return a constant, enum.
  5. Prefer “Optional.orElseGet” in the situations mentioned in 1,2 and 3rd points.

I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder

Create JPA EntityManager without persistence.xml configuration file

With plain JPA, assuming that you have a PersistenceProvider implementation (e.g. Hibernate), you can use the PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method to bootstrap an EntityManagerFactory without needing a persistence.xml.

However, it's annoying that you have to implement the PersistenceUnitInfo interface, so you are better off using Spring or Hibernate which both support bootstrapping JPA without a persistence.xml file:

this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
    this.persistenceUnitInfo, 
    getJpaPropertyMap()
);

Where the PersistenceUnitInfo is implemented by the Spring-specific MutablePersistenceUnitInfo class.

How to navigate through textfields (Next / Done Buttons)

I've just created new Pod when dealing with this stuff GNTextFieldsCollectionManager. It automatically handles next/last textField problem and is very easy to use:

[[GNTextFieldsCollectionManager alloc] initWithView:self.view];

Grabs all textfields sorted by appearing in view hierarchy (or by tags), or you can specify your own array of textFields.

How to remove all event handlers from an event

removes all handlers for button: save.RemoveEvents();

public static class EventExtension
{
    public static void RemoveEvents<T>(this T target) where T : Control
    {
       var propInfo = typeof(T).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
        var list = (EventHandlerList)propInfo.GetValue(target, null);
        list.Dispose();
    }
}

Set background colour of cell to RGB value of data in cell

Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...

Put this function into a new module:

Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
  On Error Resume Next
  x.Interior.Color = RGB(R, G, B)
  x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function

Then use this formula in your sheet, for example in cell D2:

=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")

Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2 to C2. The font color is a contrasting white or black.

Detecting input change in jQuery?

There are jQuery events like keyup and keypress which you can use with input HTML Elements. You could additionally use the blur() event.

What is the facade design pattern?

All design patterns are some classes arranged in some way or other that suits a specific application. The purpose of facade pattern is to hide the complexity of an operation or operations. You can see an example and learn facade pattern from http://preciselyconcise.com/design_patterns/facade.php

Adding an identity to an existing column

As I understood in normal cases we are creating a table with Primary key which is having Identity property
So Rename or Delete a column which is associated with Primary Key constraint will not be possible because constraint Rules are validating column structure.
Tto achieve this we have to process some steps in the following way:
Let us assume TableName = 'Employee' and ColumnName = 'EmployeeId'

1. Add new column 'EmployeeId_new' in the 'Employee' table
ALTER TABLE Employee ADD EmployeeId_new INT IDENTITY(1,1)

  1. Now remove column 'EmployeeId' from 'Employee' table
    ALTER TABLE Employee DROP COLUMN EmployeeId

  2. This will throw error because of Primary Key Constraint rules are applicable and validating column structure.
    *### 'Msg 5074, Level 16, State 1, Line 1 The object [PK_dbo.Employee] is dependent on colmn [EmployeeId].'###

  3. So we have to remove the Primary Key constraint first from the table 'Employee' then we can remove the column
    ALTER TABLE Employee DROP constraint [PK_dbo.Employee]

  4. Now we can remove the column 'EmployeeId' from 'Employee' table as did in the previous step where we got error
    ALTER TABLE Employee DROP COLUMN EmployeeId

  5. Now Column 'EmployeeId' removed from table So we will Rename the newly added new column 'EmployeeId_new' with 'EmployeeId'
    sp_rename 'Employee.EmployeeId', 'EmployeeId_new', 'COLUMN'

  6. To rearrange the table in the same form as It was, we have to add Primary Key Constraint for the column 'EmployeeId'
    ALTER TABLE Employee add constraint [PK_dbo.Employee] primary key (EmployeeId)

8. Now the table 'Employee' with 'EmployeeId' is modified for Identity rules along with existing primary key constraint

Compare object instances for equality by their attributes

When comparing instances of objects, the __cmp__ function is called.

If the == operator is not working for you by default, you can always redefine the __cmp__ function for the object.

Edit:

As has been pointed out, the __cmp__ function is deprecated since 3.0. Instead you should use the “rich comparison” methods.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-

viewDidLoad()
    {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        var width = UIScreen.main.bounds.width
        layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
    width = width - 10
    layout.itemSize = CGSize(width: width / 2, height: width / 2)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView!.collectionViewLayout = layout
    }

Highest Salary in each department

select a.*
 from EmpDetails a
 inner join 
 (
 select DeptID,max(Salary) as Salary
 from EmpDetails group by DeptID  
 )b 
on a.DeptID = b.DeptID and a.Salary = b.Salary

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

Convert String with Dot or Comma as decimal separator to number in JavaScript

The perfect solution

accounting.js is a tiny JavaScript library for number, money and currency formatting.

Check this for ref

How to increase heap size of an android application?

Increasing Java Heap unfairly eats deficit mobile resurces. Sometimes it is sufficient to just wait for garbage collector and then resume your operations after heap space is reduced. Use this static method then.

Refused to apply inline style because it violates the following Content Security Policy directive

Well, I think it is too late and many others have the solution so far.

But I hope this can Help:

I'm using react for an identity server so 'unsafe-inline' is not an option at all. If you look at your console and actually read the CSP docs, you might find that there are three options for solving the issue:

  1. 'unsafe-inline' as it says is unsafe if your project is using CSPs is for one reason and it is like throwing out the complete policy, will be the same to no have CSP policy at all

    1. 'sha-XXXCODE' this is good, safe but not optimal because there is a lot of manual work and every compilation the SHA might change so it will become easily a nightmare, use only when the script or style is unlikely to change and there are few references

    2. Nonce. This is the winner!

Nonce works in the similar way as scripts

CSP HEADER ///csp stuff nonce-12331

<script nonce="12331">
   //script content
</script>

Because the nonce in the csp is the same that the tag, the script will be executed

In the case of inline styles, the nonce also came in the form of attribute so the same rules apply.

so generate the nonce and put it on your inline scritps

If you are using webpack maybe you are using the style-loader

the following code will do the trick


module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Iterating over dictionaries using 'for' loops

To iterate over keys, it is slower but better to use my_dict.keys(). If you tried to do something like this:

for key in my_dict:
    my_dict[key+"-1"] = my_dict[key]-1

it would create a runtime error because you are changing the keys while the program is running. If you are absolutely set on reducing time, use the for key in my_dict way, but you have been warned.

How to include a Font Awesome icon in React's render()

Alexander's answer from above really helped me out!

I was trying to get social accounts icons in the footer of my app I created with ReactJS so that I could easily add a hover state to them while also having them link my social accounts. This is what I ended up having to do:

$ npm i --save @fortawesome/fontawesome-free-brands

Then at the top of my footer component I included this:

import React from 'react';
import './styles/Footer.css';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import {faTwitter, faLinkedin, faGithub} from '@fortawesome/fontawesome-free-brands';

My component then looked like this:

<a href='https://github.com/yourusernamehere'>
  <FontAwesomeIcon className ='font-awesome' icon={faGithub} />
</a>

Worked like a charm.

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

ParseError: not well-formed (invalid token) using cElementTree

See this answer to another question and the according part of the XML spec.

The backspace U+0008 is an invalid character in XML documents. It must be represented as escaped entity &#8; and cannot occur plainly.

If you need to process this XML snippet, you must replace \x08 in s before feeding it into an XML parser.

Multiple bluetooth connection

Two UE Boom Bluetooth speakers can form a stereo, which means the phone can stream simultaneously to two Bluetooth devices. The reason is Bluetooth 4.0 can support up to two synchronous connection oriented (SCO) links on the same piconet, and A2DP is based on SCO link.

Your demand "bluetooth chat" is based on SPP profile, and SPP is based on RFCOMM protocol. Luckily even Bluetooth 2.1 can support multiple RFCOMM channels, so yes, you can have multiple bluetooth connection to chat with each other.

An error occurred while executing the command definition. See the inner exception for details

This occurs when you specify the different name for repository table name and database table name. Please check your table name with database and repository.

Java - ignore exception and continue

LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..

Custom pagination view in Laravel 5

Thanks to MantisD's post, for Bootstrap 4 this worked nicely.

<?php
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <div id="news_paginate" class="dataTables_paginate paging_simple_numbers">
        <ul class="pagination">
            <li id="news_previous" class="paginate_button page-item previous {{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
                <a class="page-link" tabindex="0" href="{{ $paginator->url(1) }}">Previous</a>
            </li>
            @for ($i = 1; $i <= $paginator->lastPage(); $i++)
                <?php
                    $half_total_links = floor($link_limit / 2);
                    $from = $paginator->currentPage() - $half_total_links;
                    $to = $paginator->currentPage() + $half_total_links;
                    if ($paginator->currentPage() < $half_total_links) {
                        $to += $half_total_links - $paginator->currentPage();
                    }
                    if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                        $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
                    }
                ?>
                @if ($from < $i && $i < $to)
                    <li class="paginate_button page-item {{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                        <a class="page-link" href="{{ $paginator->url($i) }}">{{ $i }}</a>
                    </li>
                @endif
            @endfor
            <li id="news_next" class="paginate_button page-item {{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
                @if($paginator->currentPage() == $paginator->lastPage())
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()) }}" >End</a>
                @else
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
                @endif
            </li>
        </ul>
    </div>
@endif

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}

How can I sort a dictionary by key?

Dictionaries themselves do not have ordered items as such, should you want to print them etc to some order, here are some examples:

In Python 2.4 and above:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict):
    print "%s: %s" % (key, mydict[key])

gives:

alan: 2
bob: 1
carl: 40
danny: 3

(Python below 2.4:)

keylist = mydict.keys()
keylist.sort()
for key in keylist:
    print "%s: %s" % (key, mydict[key])

Source: http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

Could not load file or assembly Exception from HRESULT: 0x80131040

Add following dll files to bin folder:

DotNetOpenAuth.AspNet.dll
DotNetOpenAuth.Core.dll
DotNetOpenAuth.OAuth.Consumer.dll
DotNetOpenAuth.OAuth.dll
DotNetOpenAuth.OpenId.dll
DotNetOpenAuth.OpenId.RelyingParty.dll

If you will not need them, delete dependentAssemblies from config named 'DotNetOpenAuth.Core' etc..

How to parse a JSON object to a TypeScript Object

Try to use constructor procedure in your class.

Object.assign

is a key

Please take a look on this sample:

class Employee{
    firstname: string;
    lastname: string;
    birthdate: Date;
    maxWorkHours: number;
    department: string;
    permissions: string;
    typeOfEmployee: string;
    note: string;
    lastUpdate: Date;

    constructor(original: Object) { 
        Object.assign(this, original);
    }
}

let e = new Employee({
    "department": "<anystring>",
    "typeOfEmployee": "<anystring>",
    "firstname": "<anystring>",
    "lastname": "<anystring>",
    "birthdate": "<anydate>",
    "maxWorkHours": 3,
    "username": "<anystring>",
    "permissions": "<anystring>",
    "lastUpdate": "<anydate>"
});
console.log(e);

Converting a double to an int in C#

Because Convert.ToInt32 rounds:

Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

...while the cast truncates:

When you convert from a double or float value to an integral type, the value is truncated.

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).

Jquery DatePicker Set default date

Today date:

$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });

15 days from today:

$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });

jQuery ui docs

How to display request headers with command line curl

I believe the command line switch you are looking for to pass to curl is -I.

Example usage:

$ curl -I http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287  
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:05 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1

Additionally, if you encounter a response HTTP status code of 301, you might like to also pass a -L argument switch to tell curl to follow URL redirects, and, in this case, print the headers of all pages (including the URL redirects), illustrated below:

$ curl -I -L http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 302 Found
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Set-Cookie: UID=b8c37e33defde51cf91e1e03e51657da
Location: noaccess.php
Content-Type: text/html

HTTP/1.1 200 OK
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html

How do you round UP a number in Python?

You could use rond

cost_per_person = round(150 / 2, 2)

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

NOTE: if you are experiencing this issue in your CI pipeline, it is usually because npm runs npm ci instead of npm install. npm ci requires an accurate package-lock.json.

To fix this, whenever you are modifying packages in package.json (e.g. moving packages from devDependencies to Dependencies like I was doing) you should regenerate package-lock.json in your repository by running these commands locally, and then push the changes upstream:

rm -rf node_modules
npm install
git commit package-lock.json
git push

mailto link with HTML body

It's not quite what you want, but it's possible using modern javascript to create an EML file on the client and stream that to the user's file system, which should open a rich email containing HTML in their mail program, such as Outlook:

https://stackoverflow.com/a/27971771/8595398

Here's a jsfiddle of an email containing images and tables: https://jsfiddle.net/seanodotcom/yd1n8Lfh/

HTML

<!-- https://jsfiddle.net/seanodotcom/yd1n8Lfh -->
<textarea id="textbox" style="width: 300px; height: 600px;">
To: User <[email protected]>
Subject: Subject
X-Unsent: 1
Content-Type: text/html

<html>
<head>
<style>
    body, html, table {
        font-family: Calibri, Arial, sans-serif;
    }
    .pastdue { color: crimson; }
    table {
        border: 1px solid silver;
        padding: 6px;
    }
    thead {
        text-align: center;
        font-size: 1.2em;
        color: navy;
        background-color: silver;
        font-weight: bold;
    }
    tbody td {
        text-align: center;
    }
</style>
</head>
<body>
<table width=100%>
    <tr>
        <td><img src="http://www.laurell.com/images/logo/laurell_logo_storefront.jpg" width="200" height="57" alt=""></td>
        <td align="right"><h1><span class="pastdue">PAST DUE</span> INVOICE</h1></td>
    </tr>
</table>
<table width=100%>
    <thead>
        <th>Invoice #</th>
        <th>Days Overdue</th>
        <th>Amount Owed</th>
    </thead>
    <tbody>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    </tbody>
</table>
</body>
</html>
</textarea> <br>
<button id="create">Create file</button><br><br>
<a download="message.eml" id="downloadlink" style="display: none">Download</a>

Javascript

(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }
    textFile = window.URL.createObjectURL(data);
    return textFile;
  };

  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');
  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

COPYing a file in a Dockerfile, no such file or directory?

Running docker build . -f docker/development/Dockerfile worked, which allows you to run your docker file from a specified directory other than the root of your application.

Use -f or --file to specify the name and location of the Dockerfile.

This happened to me when trying to run the docker file from a different directory.

I had the COPY failed: stat /var/lib/docker/tmp/docker-builder929708051/XXXX: no such file or directory and managed to resolve this by specifying the docker file.

It was docker build docker/development/Dockerfile that caused this issue for me.

I found it strange at first because when i had the Dockerfile in the apps root directory it worked fine. This will help if you want to manage your environment docker files a little better.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

JQuery, select first row of table

This is a better solution, using:

$("table tr:first-child").has('img')

I get Access Forbidden (Error 403) when setting up new alias

try this

sudo chmod -R 0777 /opt/lampp/htdocs/testproject

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I had the same issue using a node module with a react application written in typescript. The module was successfully installed using npm i --save my-module. It is written in javascript and exports a Client class.

With:

import * as MyModule from 'my-module';
let client: MyModule.Client = new MyModule.Client();

Compilation fails with the error:

Could not find a declaration file for module 'my-module'. 
'[...]/node_modules/my-module/lib/index.js' implicitly has an 'any' type.
  Try `npm install @types/my-module` if it exists or add a new declaration (.d.ts) file containing `declare module 'my-module';`

@types/my-module does not exist, so I added a my-module.d.ts file next to the one where my-module is imported, with the suggested line. I then got the error:

Namespace '"my-module"' has no exported member 'Client'.

The client is actually exported and works normally if I use it in a js app. Also, the previous message tells me that the compiler is looking in the right file (/node_modules/my-module/lib/index.js is defined in my-module/package.json "main" element).

I solved the issue by telling the compiler I do not care about implicit any, that is, I set to false the following line of the tsconfig.json file:

    "noImplicitAny": false,

How to position background image in bottom right corner? (CSS)

Did you try something like:

body {background: url('[url to your image]') no-repeat right bottom;}

List of installed gems?

Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:

Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil

How to avoid the "divide by zero" error in SQL?

There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

Get current date, given a timezone in PHP?

I have created some simple function you can use to convert time to any timezone :

function convertTimeToLocal($datetime,$timezone='Europe/Dublin') {
        $given = new DateTime($datetime, new DateTimeZone("UTC"));
        $given->setTimezone(new DateTimeZone($timezone));
        $output = $given->format("Y-m-d"); //can change as per your requirement
        return $output;
}

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

Importing Excel files into R, xlsx or xls

This new package looks nice http://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf It doesn't require rJava and is using 'Rcpp' for speed.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

How to disable a particular checkstyle rule for a particular line of code?

Check out the use of the supressionCommentFilter at http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter. You'll need to add the module to your checkstyle.xml

<module name="SuppressionCommentFilter"/>

and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.

//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON

Or even better, use this more tweaked version:

<module name="SuppressionCommentFilter">
    <property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
</module>

which allows you to turn off specific checks for specific lines of code:

//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch

*Note: you'll also have to add the FileContentsHolder:

<module name="FileContentsHolder"/>

See also

<module name="SuppressionFilter">
    <property name="file" value="docs/suppressions.xml"/>
</module>

under the SuppressionFilter section on that same page, which allows you to turn off individual checks for pattern matched resources.

So, if you have in your checkstyle.xml:

<module name="ParameterNumber">
   <property name="id" value="maxParameterNumber"/>
   <property name="max" value="3"/>
   <property name="tokens" value="METHOD_DEF"/>
</module>

You can turn it off in your suppression xml file with:

<suppress id="maxParameterNumber" files="YourCode.java"/>

Another method, now available in Checkstyle 5.7 is to suppress violations via the @SuppressWarnings java annotation. To do this, you will need to add two new modules (SuppressWarningsFilter and SuppressWarningsHolder) in your configuration file:

<module name="Checker">
   ...
   <module name="SuppressWarningsFilter" />
   <module name="TreeWalker">
       ...
       <module name="SuppressWarningsHolder" />
   </module>
</module> 

Then, within your code you can do the following:

@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {

or, for multiple suppressions:

@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {

NB: The "checkstyle:" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

jQuery ID starts with

try:

$("td[id^=" + value + "]")

Check if int is between two numbers

COBOL allows that (I am sure some other languages do as well). Java inherited most of it's syntax from C which doesn't allow it.

SimpleXML - I/O warning : failed to load external entity

simplexml_load_file() interprets an XML file (either a file on your disk or a URL) into an object. What you have in $feed is a string.

You have two options:

  • Use file_get_contents() to get the XML feed as a string, and use e simplexml_load_string():

    $feed = file_get_contents('...');
    $items = simplexml_load_string($feed);
    
  • Load the XML feed directly using simplexml_load_file():

    $items = simplexml_load_file('...');
    

find vs find_by vs where

Apart from accepted answer, following is also valid

Model.find() can accept array of ids, and will return all records which matches. Model.find_by_id(123) also accept array but will only process first id value present in array

Model.find([1,2,3])
Model.find_by_id([1,2,3])

How to center icon and text in a android button with width set to "fill parent"

This may be an old/closed thread but I've search everywhere didnt find something useful, until I decided to create my own solution. If theres anyone here trying to look for answer try this one, might save you a minute of thinking

          <LinearLayout
            android:id="@+id/llContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/selector"
            android:clickable="true"
            android:gravity="center"
            android:orientation="vertical"
            android:padding="10dp"
            android:textStyle="bold">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="This is a text" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/icon_image />


        </LinearLayout>

Because Linear layout act as the container and the one who has the selector, when you click the entire linear layout it would look just how it should it be. if you want it to be both centered, use relative insteaf. If you want it centered horizontally change the orientation to horizontal.

Take note DO NOT forget to add android:clickable="true" to your main container (relative or linear) for the action to take place.

Again this may be old thread but may still help someone there.

-cheers hope it helps- happycodings.

jQuery: Setting select list 'selected' based on text, failing strangely

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

How can you run a Java program without main method?

Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:

public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

Exception in thread "main" java.lang.NoSuchMethodError: main

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).

Here an alternative is to write your own launcher, this way you can define entry points as you want.

In the article JVM Launcher you will find the necessary information to get started:

This article explains how can we create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.

Going from MM/DD/YYYY to DD-MMM-YYYY in java

final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));

Java 8 LocalDate

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

SyntaxError: Unexpected token function - Async Await Nodejs

I too had the same problem.

I was running node v 6.2 alongside using purgecss within my gulpfile. Problem only occurred when I created a new Laravel project; up until that point, I never had an issue with purgecss.

Following @Quentin's statement - how node versions prior to 7.6 do not support async functions - I decided to update my node version to 9.11.2

This worked for me:

1-

$ npm install -g n

$ n 9.11.2

2-

delete 'node_modules' from the route directory

3-

$ npm install

Still not sure how node/purgecss worked prior to updating.. but this did the trick.

Attach to a processes output for viewing

How would I 'attach' a console/terminal-view to an applications output so I can see what it may be saying?

About this question, I know it is possible to catch the output, even when you didn't launch sceen command before launching the processus.

While I never tried it, I've found an interesting article which explains how to do using GDB (and without restarting your process).

redirecting-output-from-a-running-process

Basically:

  1. Check the open files list for your process, thanks to /proc/xxx/fd
  2. Attach your process with GDB
  3. While it is paused, close the file you are interested in, calling close() function (you can any function of your process in GDB. I suspect you need debug symbols in your process..)
  4. Open the a new file calling the create() or open() function. (Have a look in comments at the end, you'll see people suggest to use dup2() to ensure the same handle will be in use)
  5. Detach the process and let in run.

By the way, if you are running a linux OS on i386 box, comments are talking about a better tool to redirect output to a new console : 'retty' . If so, consider its use.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

I used to solve this issue by deleting the corresponding failed to download artifact directory in my local repo. Next time I run the maven command the artifact download is triggered again. Therefore I'd say it's a client side setting.

Nexus side (server repo side), this issue is solved configuring a scheduled task. Client side, this is done using -U, as you already pointed out.

80-characters / right margin line in Sublime Text 3

For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.

This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.

Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts

On stackoverflow, see:

Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?

MattDMo's answer here: What is the default font of Sublime Text?

I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)

Other viewing environments that benefit from shorter lines: github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.

PHP Get all subdirectories of a given directory

Try this code:

<?php
$path = '/var/www/html/project/somefolder';

$dirs = array();

// directory handle
$dir = dir($path);

while (false !== ($entry = $dir->read())) {
    if ($entry != '.' && $entry != '..') {
       if (is_dir($path . '/' .$entry)) {
            $dirs[] = $entry; 
       }
    }
}

echo "<pre>"; print_r($dirs); exit;

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

Let uses a more immediate block level limited scope whereas var is function scope or global scope typically.

It seems let was chosen most likely because it is found in so many other languages to define variables, such as BASIC, and many others.

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

'adb' is not recognized as an internal or external command, operable program or batch file

I recommand you using PowerShell

Set Android Studio Terminal to PowerShell:

Settings > Tools > Terminal > Shell path = pwsh.exe (instead of cmd.exe)

Open Terminal on Android Studio

PowerShell 7.0.1
Copyright (c) Microsoft Corporation. All rights reserved.

https://aka.ms/powershell
Type 'help' to get help.

PS >

Test the path for adb.exe

# `pikachu` should be replace your username
PS > test-path "C:\Users\pikachu\AppData\Local\Android\sdk\platform-tools"
True

Open your powershell profile file in your text editor

PS > notepad $profile

add below line, save and exit

# `pikachu` should be replaced with your username
$env:PATH+="C:\Users\pikachu\AppData\Local\Android\sdk\platform-tools"

re-open Terminal and try adb

PS > adb
Android Debug Bridge version 1.0.41
Version 30.0.1-6435776
Installed as C:\Users\hdformat\AppData\Local\Android\sdk\platform-tools\adb.exe

global options:
 -a         listen on all network interfaces, not just localhost
 -d         use USB device (error if multiple devices connected)
 -e         use TCP/IP device (error if multiple TCP/IP devices available)
 -s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)
 -t ID      use device with given transport id
 -H         name of adb server host [default=localhost]
 -P         port of adb server [default=5037]

Error:java: invalid source release: 8 in Intellij. What does it mean?

It can be simply overcome by setting on Project Structure. You just need to select the right path for related version of JDK. Select new on dependencies tab, and choose the path. It's done!

enter image description here

What is an alternative to execfile in Python 3?

Also, while not a pure Python solution, if you're using IPython (as you probably should anyway), you can do:

%run /path/to/filename.py

Which is equally easy.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Sorry its late, but I guess it would be of help to those who land here finding a solution to similar problem. The set clause should come right after the update clause. So rearranging your query with a bit change does the work.

UPDATE DHE.dbo.tblAccounts 
SET DHE.dbo.tblAccounts.ControllingSalesRep
    = DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts 
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink 
    ON DHE.dbo.tblAccounts.AccountCode
        = DHE_Import.tblSalesRepsAccountsLink.AccountCode 

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

Magento - Retrieve products with a specific attribute value

I have added line

$this->_productCollection->addAttributeToSelect('releasedate');

in

app/code/core/Mage/Catalog/Block/Product/List.php on line 95

in function _getProductCollection()

and then call it in

app/design/frontend/default/hellopress/template/catalog/product/list.phtml

By writing code

<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>

Now it is working in Magento 1.4.x

How to filter multiple values (OR operation) in angularJS

I wrote this for strings AND functionality (I know it's not the question but I searched for it and got here), maybe it can be expanded.

String.prototype.contains = function(str) {
  return this.indexOf(str) != -1;
};

String.prototype.containsAll = function(strArray) {
  for (var i = 0; i < strArray.length; i++) {
    if (!this.contains(strArray[i])) {
      return false;
    }
  }
  return true;
}

app.filter('filterMultiple', function() {
  return function(items, filterDict) {
    return items.filter(function(item) {
      for (filterKey in filterDict) {
        if (filterDict[filterKey] instanceof Array) {
          if (!item[filterKey].containsAll(filterDict[filterKey])) {
            return false;
          }
        } else {
          if (!item[filterKey].contains(filterDict[filterKey])) {
            return false;
          }
        }
      }
      return true;
    });  
  };
});

Usage:

<li ng-repeat="x in array | filterMultiple:{key1: value1, key2:[value21, value22]}">{{x.name}}</li>

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

How can I get the external SD card path for Android 4.0+?

This solution (assembled from other answers to this question) handles the fact (as mentioned by @ono) that System.getenv("SECONDARY_STORAGE") is of no use with Marshmallow.

Tested and working on:

  • Samsung Galaxy Tab 2 (Android 4.1.1 - Stock)
  • Samsung Galaxy Note 8.0 (Android 4.2.2 - Stock)
  • Samsung Galaxy S4 (Android 4.4 - Stock)
  • Samsung Galaxy S4 (Android 5.1.1 - Cyanogenmod)
  • Samsung Galaxy Tab A (Android 6.0.1 - Stock)

    /**
     * Returns all available external SD-Card roots in the system.
     *
     * @return paths to all available external SD-Card roots in the system.
     */
    public static String[] getStorageDirectories() {
        String [] storageDirectories;
        String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            List<String> results = new ArrayList<String>();
            File[] externalDirs = applicationContext.getExternalFilesDirs(null);
            for (File file : externalDirs) {
                String path = file.getPath().split("/Android")[0];
                if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
                        || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){
                    results.add(path);
                }
            }
            storageDirectories = results.toArray(new String[0]);
        }else{
            final Set<String> rv = new HashSet<String>();
    
            if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                Collections.addAll(rv, rawSecondaryStorages);
            }
            storageDirectories = rv.toArray(new String[rv.size()]);
        }
        return storageDirectories;
    }
    

MYSQL import data from csv using LOAD DATA INFILE

If you are running LOAD DATA LOCAL INFILE from the windows shell, and you need to use OPTIONALLY ENCLOSED BY '"', you will have to do something like this in order to escape characters properly:

"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysql" -u root --password=%password% -e "LOAD DATA LOCAL INFILE '!file!' INTO TABLE !table! FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"^""' LINES TERMINATED BY '\n' IGNORE 1 LINES" --verbose --show-warnings > mysql_!fname!.out

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Replace preg_replace() e modifier with preg_replace_callback

preg_replace shim with eval support

This is very inadvisable. But if you're not a programmer, or really prefer terrible code, you could use a substitute preg_replace function to keep your /e flag working temporarily.

/**
 * Can be used as a stopgap shim for preg_replace() calls with /e flag.
 * Is likely to fail for more complex string munging expressions. And
 * very obviously won't help with local-scope variable expressions.
 *
 * @license: CC-BY-*.*-comment-must-be-retained
 * @security: Provides `eval` support for replacement patterns. Which
 *   poses troubles for user-supplied input when paired with overly
 *   generic placeholders. This variant is only slightly stricter than
 *   the C implementation, but still susceptible to varexpression, quote
 *   breakouts and mundane exploits from unquoted capture placeholders.
 * @url: https://stackoverflow.com/q/15454220
 */
function preg_replace_eval($pattern, $replacement, $subject, $limit=-1) {
    # strip /e flag
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    # warn about most blatant misuses at least
    if (preg_match('/\(\.[+*]/', $pattern)) {
        trigger_error("preg_replace_eval(): regex contains (.*) or (.+) placeholders, which easily causes security issues for unconstrained/user input in the replacement expression. Transform your code to use preg_replace_callback() with a sane replacement callback!");
    }
    # run preg_replace with eval-callback
    return preg_replace_callback(
        $pattern,
        function ($matches) use ($replacement) {
            # substitute $1/$2/… with literals from $matches[]
            $repl = preg_replace_callback(
                '/(?<!\\\\)(?:[$]|\\\\)(\d+)/',
                function ($m) use ($matches) {
                    if (!isset($matches[$m[1]])) { trigger_error("No capture group for '$m[0]' eval placeholder"); }
                    return addcslashes($matches[$m[1]], '\"\'\`\$\\\0'); # additionally escapes '$' and backticks
                },
                $replacement
            );
            # run the replacement expression
            return eval("return $repl;");
        },
        $subject,
        $limit
    );
}

In essence, you just include that function in your codebase, and edit preg_replace to preg_replace_eval wherever the /e flag was used.

Pros and cons:

  • Really just tested with a few samples from Stack Overflow.
  • Does only support the easy cases (function calls, not variable lookups).
  • Contains a few more restrictions and advisory notices.
  • Will yield dislocated and less comprehensible errors for expression failures.
  • However is still a usable temporary solution and doesn't complicate a proper transition to preg_replace_callback.
  • And the license comment is just meant to deter people from overusing or spreading this too far.

Replacement code generator

Now this is somewhat redundant. But might help those users who are still overwhelmed with manually restructuring their code to preg_replace_callback. While this is effectively more time consuming, a code generator has less trouble to expand the /e replacement string into an expression. It's a very unremarkable conversion, but likely suffices for the most prevalent examples.

To use this function, edit any broken preg_replace call into preg_replace_eval_replacement and run it once. This will print out the according preg_replace_callback block to be used in its place.

/**
 * Use once to generate a crude preg_replace_callback() substitution. Might often
 * require additional changes in the `return …;` expression. You'll also have to
 * refit the variable names for input/output obviously.
 *
 * >>>  preg_replace_eval_replacement("/\w+/", 'strtopupper("$1")', $ignored);
 */
function preg_replace_eval_replacement($pattern, $replacement, $subjectvar="IGNORED") {
    $pattern = preg_replace('/(\W[a-df-z]*)e([a-df-z]*)$/i', '$1$2', $pattern);
    $replacement = preg_replace_callback('/[\'\"]?(?<!\\\\)(?:[$]|\\\\)(\d+)[\'\"]?/', function ($m) { return "\$m[{$m[1]}]"; }, $replacement);
    $ve = "var_export";
    $bt = debug_backtrace(0, 1)[0];
    print "<pre><code>
    #----------------------------------------------------
    # replace preg_*() call in '$bt[file]' line $bt[line] with:
    #----------------------------------------------------
    \$OUTPUT_VAR = preg_replace_callback(
        {$ve($pattern, TRUE)},
        function (\$m) {
            return {$replacement};
        },
        \$YOUR_INPUT_VARIABLE_GOES_HERE
    )
    #----------------------------------------------------
    </code></pre>\n";
}

Take in mind that mere copy&pasting is not programming. You'll have to adapt the generated code back to your actual input/output variable names, or usage context.

  • Specificially the $OUTPUT = assignment would have to go if the previous preg_replace call was used in an if.
  • It's best to keep temporary variables or the multiline code block structure though.

And the replacement expression may demand more readability improvements or rework.

  • For instance stripslashes() often becomes redundant in literal expressions.
  • Variable-scope lookups require a use or global reference for/within the callback.
  • Unevenly quote-enclosed "-$1-$2" capture references will end up syntactically broken by the plain transformation into "-$m[1]-$m[2].

The code output is merely a starting point. And yes, this would have been more useful as an online tool. This code rewriting approach (edit, run, edit, edit) is somewhat impractical. Yet could be more approachable to those who are accustomed to task-centric coding (more steps, more uncoveries). So this alternative might curb a few more duplicate questions.

Setting initial values on load with Select2 with Ajax

var elem = $("#container").find("[name=elemMutliOption]");
for (var i = 0; i < arrDynamicList.length; i++)
{
   elem.find("option[value=" + arrDynamicList[i] + "]").attr("selected", "selected");
}
elem.select2().trigger("change");

This will work for people who are using the same view for multiple section in the page, with that being said it will work the same way for auto-setting defaults in your page OR better a EDIT page.

The "FOR" goes through the array that has existing options already loaded in the DOM.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

Difference between Spring MVC and Struts MVC

The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.

MySQL "between" clause not inclusive?

Is the field you are referencing in your query a Date type or a DateTime type?

A common cause of the behavior you describe is when you use a DateTime type where you really should be using a Date type. That is, unless you really need to know what time someone was born, just use the Date type.

The reason the final day is not being included in your results is the way that the query is assuming the time portion of the dates that you did not specify in your query.

That is: Your query is being interpreted as up to Midnight between 2011-01-30 and 2011-01-31, but the data may have a value sometime later in the day on 2011-01-31.

Suggestion: Change the field to the Date type if it is a DateTime type.

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

How to solve npm error "npm ERR! code ELIFECYCLE"

I recommend you update your node version to the latest node version recommended by your application or for short update your node version. I encountered this same problem using node version 11.1 but my application was recommending atleast version 10.x.x or 12.x.x I tried all the suggested reply on this thread but non seemed to work for me untill only when i updated my node version to the recommended latest version .i.e. version 12.16.3 then my application ran. enter image description here

How to automatically generate a stacktrace when my program crashes

I found that @tgamblin solution is not complete. It cannot handle with stackoverflow. I think because by default signal handler is called with the same stack and SIGSEGV is thrown twice. To protect you need register an independent stack for the signal handler.

You can check this with code below. By default the handler fails. With defined macro STACK_OVERFLOW it's all right.

#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <cassert>

using namespace std;

//#define STACK_OVERFLOW

#ifdef STACK_OVERFLOW
static char stack_body[64*1024];
static stack_t sigseg_stack;
#endif

static struct sigaction sigseg_handler;

void handler(int sig) {
  cerr << "sig seg fault handler" << endl;
  const int asize = 10;
  void *array[asize];
  size_t size;

  // get void*'s for all entries on the stack
  size = backtrace(array, asize);

  // print out all the frames to stderr
  cerr << "stack trace: " << endl;
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  cerr << "resend SIGSEGV to get core dump" << endl;
  signal(sig, SIG_DFL);
  kill(getpid(), sig);
}

void foo() {
  foo();
}

int main(int argc, char **argv) {
#ifdef STACK_OVERFLOW
  sigseg_stack.ss_sp = stack_body;
  sigseg_stack.ss_flags = SS_ONSTACK;
  sigseg_stack.ss_size = sizeof(stack_body);
  assert(!sigaltstack(&sigseg_stack, nullptr));
  sigseg_handler.sa_flags = SA_ONSTACK;
#else
  sigseg_handler.sa_flags = SA_RESTART;  
#endif
  sigseg_handler.sa_handler = &handler;
  assert(!sigaction(SIGSEGV, &sigseg_handler, nullptr));
  cout << "sig action set" << endl;
  foo();
  return 0;
} 

iOS Remote Debugging

Vorlon.JS can be used for remote debugging of iOS or any other client.

  1. Just install it globally using npm i -g vorlon
  2. Start server using vorlon
  3. With the server is running, open http://localhost:1337 in your browser to see the Vorlon.JS dashboard
  4. The last step is to enable Vorlon.JS by adding this script tag to your app:
    <script src="http://<yourExternalIP>:1337/vorlon.js"></script>
  5. All connected clients e.g. iPhone, Android will become available in client list on Vorlon.JS dashboard enter image description here

Note that this approach can also be used to debug apps not running on localhost using ngrok. See https://stackoverflow.com/a/45443203/2073920 for details.

Disclaimer

I am just a user and I am not affiliated with Vorlon.JS and ngrok

Switch statement with returns -- code correctness

I would say remove them and define a default: branch.

How do I fire an event when a iframe has finished loading in jQuery?

Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:

    window.onload = function () {


    //creating an iframe element
    var ifr = document.createElement('iframe');
    document.body.appendChild(ifr);

    // making the iframe fill the viewport
    ifr.width  = '100%';
    ifr.height = window.innerHeight;

    // continuously checking to see if the pdf file has been loaded
     self.interval = setInterval(function () {
        if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
            clearInterval(self.interval);

            console.log("loaded");
            //You can do print here: ifr.contentWindow.print();
        }
    }, 100); 

    ifr.src = src;
}

remote rejected master -> master (pre-receive hook declined)

simple answer

$ heroku config:set DISABLE_COLLECTSTATIC=1

after

$ git push heroku master

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

What's the best three-way merge tool?

Diffuse is an easy to use three-way merge tool. It supports all of the platforms and version control systems you mentioned, and it can compare more than three files at the same time.

enter image description here

How to define constants in ReactJS

Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases

You can use ES7 statics:

npm install babel-preset-stage-0

And then add "stage-0" to .babelrc presets:

{
    "presets": ["es2015", "react", "stage-0"]
}

Afterwards, you go

class Component extends React.Component {
    static foo = 'bar';
    static baz = {a: 1, b: 2}
}

And then you use them like this:

Component.foo

How can I get the last day of the month in C#?

try this. It will solve your problem.

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);

How to access custom attributes from event object in React?

As of React v16.1.1 (2017), here is the official solution: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

TLDR: OP should do:

render: function() {
...
<a style={showStyle} onClick={(e) => this.removeTag(i, e)}></a>
...
removeTag: function(i, event) {
    this.setState({inputVal: i}); 
}

How do I remove duplicate items from an array in Perl?

My usual way of doing this is:

my %unique = ();
foreach my $item (@myarray)
{
    $unique{$item} ++;
}
my @myuniquearray = keys %unique;

If you use a hash and add the items to the hash. You also have the bonus of knowing how many times each item appears in the list.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

Run a command over SSH with JSch

The example provided by Mykhaylo Adamovych is very thorough and exposes most of the major features of JSch. I packaged this code (with attribution, of course) into an open-source library called Remote Session. I added JavaDoc and custom exceptions, and I also provided a facility to specify custom session parameters (RemoteConfig).

One feature that Mykhaylo's code doesn't demonstrate is how to provide an "identity" for remote system interactions. This is critical if you're going to execute commands that require super-user access (i.e. - sudo). Remote Session adds this capability in its SessionHolder.newSession() implementation:

RemoteConfig remoteConfig = RemoteConfig.getConfig();
Path keyPath = remoteConfig.getKeyPath();

if (keyPath == null) {
    throw new RemoteCredentialsUnspecifiedException();
}

String keyPass = remoteConfig.getString(RemoteSettings.SSH_KEY_PASS.key());
if (keyPass != null) {
    Path pubPath = keyPath.resolveSibling(keyPath.getFileName() + ".pub");
    jsch.addIdentity(keyPath.toString(), pubPath.toString(), keyPass.getBytes());
} else {
    jsch.addIdentity(keyPath.toString());
}

Note that this behavior is bypassed if the remote system URL includes credentials.

Another feature that Remote Session demonstrates is how to provide a known-hosts file:

if ( ! remoteConfig.getBoolean(RemoteSettings.IGNORE_KNOWN_HOSTS.key())) {
    Path knownHosts = keyPath.resolveSibling("known_hosts");
    if (knownHosts.toFile().exists()) {
        jsch.setKnownHosts(knownHosts.toString());
    }
}

Remote Session also adds a ChannelStream class that encapsulates input/output operation for the channel attached to this session. This provides the ability to accumulate the output from the remote session until a specified prompt is received:

private boolean appendAndCheckFor(String prompt, StringBuilder input, Logger logger) throws InterruptedException, IOException {
    String recv = readChannel(false);
    if ( ! ((recv == null) || recv.isEmpty())) {
        input.append(recv);
        if (logger != null) {
            logger.debug(recv);
        }
        if (input.toString().contains(prompt)) {
            return false;
        }
    }
    return !channel.isClosed();
}

Nothing too complicated, but this can greatly simplify the implementation of interactive remote operations.

Open file in a relative location in Python

Try this:

from pathlib import Path

data_folder = Path("/relative/path")
file_to_open = data_folder / "file.pdf"

f = open(file_to_open)

print(f.read())

Python 3.4 introduced a new standard library for dealing with files and paths called pathlib. It works for me!

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had a similar issue and based on above suggestions I first added "super.setIntegerProperty("loadUrlTimeoutValue", 70000);" but that did not help. So I tried Project -> Clean, that worked and I can launch the app now !

Avinash...

How can I get the order ID in WooCommerce?

I didnt test it and dont know were you need it, but:

$order = new WC_Order(post->ID);
echo $order->get_order_number();

Let me know if it works. I belive order number echoes with the "#" but you can split that if only need only the number.

Chrome, Javascript, window.open in new tab

At the moment (Chrome 39) I use this code to open a new tab:

_x000D_
_x000D_
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
_x000D_
_x000D_
_x000D_

Of course this may change in future versions of Chrome.

It is a bad idea to use this if you can't control the browser your users are using. It may not work in future versions or with different settings.

Clearing an input text field in Angular2

There are two additional ways to do it apart from the two methods mentioned in @PradeepJain's answer.

I would suggest not to use this approach and to fall back to this only as a last resort if you are not using [(ngModel)] directive and also not using data binding via [value]. Read this for more info.

Using ElementRef

app.component.html

<div>
      <input type="text" #searchInput placeholder="Search...">
      <button (click)="clearSearchInput()">Clear</button>
</div>

app.component.ts

export class App {
  @ViewChild('searchInput') searchInput: ElementRef;

  clearSearchInput(){
     this.searchInput.nativeElement.value = '';
  }
}

Using FormGroup

app.component.html

<form [formGroup]="form">
    <div *ngIf="first.invalid"> Name is too short. </div>
    <input formControlName="first" placeholder="First name">
    <input formControlName="last" placeholder="Last name">
    <button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
<button (click)="clearInputMethod1()">Clear Input Method 1</button>
<button (click)="clearInputMethod2()">Clear Input Method 2</button>

app.component.ts

export class AppComponent {
  form = new FormGroup({
    first: new FormControl('Nancy', Validators.minLength(2)),
    last: new FormControl('Drew'),
  });
  get first(): any { return this.form.get('first'); }
  get last(): any { return this.form.get('last'); }
  clearInputMethod1() { this.first.reset(); this.last.reset(); }
  clearInputMethod2() { this.form.setValue({first: '', last: ''}); }
  setValue() { this.form.setValue({first: 'Nancy', last: 'Drew'}); }
}

Try it out on stackblitz Clearing input in a FormGroup

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

Spring Boot Adding Http Request Interceptors

Below is an implementation I use to intercept each HTTP request before it goes out and the response which comes back. With this implementation, I also have a single point where I can pass any header value with the request.

public class HttpInterceptor implements ClientHttpRequestInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public ClientHttpResponse intercept(
        HttpRequest request, byte[] body,
        ClientHttpRequestExecution execution
) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
    headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}

private void traceRequest(HttpRequest request, byte[] body) throws IOException {
    logger.info("===========================Request begin======================================");
    logger.info("URI         : {}", request.getURI());
    logger.info("Method      : {}", request.getMethod());
    logger.info("Headers     : {}", request.getHeaders() );
    logger.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
    logger.info("==========================Request end=========================================");
}

private void traceResponse(ClientHttpResponse response) throws IOException {
    logger.info("============================Response begin====================================");
    logger.info("Status code  : {}", response.getStatusCode());
    logger.info("Status text  : {}", response.getStatusText());
    logger.info("Headers      : {}", response.getHeaders());
    logger.info("=======================Response end===========================================");
}}

Below is the Rest Template Bean

@Bean
public RestTemplate restTemplate(HttpClient httpClient)
{
    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    RestTemplate restTemplate=  new RestTemplate(requestFactory);
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
    if (CollectionUtils.isEmpty(interceptors))
    {
        interceptors = new ArrayList<>();
    }
    interceptors.add(new HttpInterceptor());
    restTemplate.setInterceptors(interceptors);

    return restTemplate;
}

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null

ORDER BY the IN value list

And here's another solution that works and uses a constant table (http://www.postgresql.org/docs/8.3/interactive/sql-values.html):

SELECT * FROM comments AS c,
(VALUES (1,1),(3,2),(2,3),(4,4) ) AS t (ord_id,ord)
WHERE (c.id IN (1,3,2,4)) AND (c.id = t.ord_id)
ORDER BY ord

But again I'm not sure that this is performant.

I've got a bunch of answers now. Can I get some voting and comments so I know which is the winner!

Thanks All :-)

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

Determining Referer in PHP

Using $_SERVER['HTTP_REFERER']

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

if (!empty($_SERVER['HTTP_REFERER'])) {
    header("Location: " . $_SERVER['HTTP_REFERER']);
} else {
    header("Location: index.php");
}
exit;

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

The above all approaches are correct and may be working . I have created a working demo following the above guide and tested on 2.x to 5.x

You can clone from Github

The important thing to play around is in Main Activity

toolbar = (Toolbar) findViewById(R.id.toolbar);
res = this.getResources();

this.setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
    ScrimInsetsFrameLayout scrimInsetsFrameLayout = (ScrimInsetsFrameLayout)
            findViewById(R.id.linearLayout);
    scrimInsetsFrameLayout.setOnInsetsCallback(this);
} 

and the call back

@Override
public void onInsetsChanged(Rect insets) {
    Toolbar toolbar = this.toolbar;
    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)
        toolbar.getLayoutParams();
    lp.topMargin = insets.top;
    int top = insets.top;
    insets.top += toolbar.getHeight();
    toolbar.setLayoutParams(lp);
    insets.top = top; // revert
}

Absolutely the Theme for V21 does the magic

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- API 21 theme customizations can go here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/accent_material_light</item>
    <item name="windowActionModeOverlay">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
    <item name="android:windowTranslucentStatus">true</item>
</style>

and the ScrimInsetsFrameLayout

Now this come more easy with new Design Support library

compile 'com.android.support:design:22.2.0'

clone from @Chris Banes https://github.com/chrisbanes/cheesesquare

How to fix '.' is not an internal or external command error

Just leave out the "dot-slash" ./:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Though, if you wanted to, you could use .\ and it would work.

D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"

How can I output UTF-8 from Perl?

do in your shell: $ env |grep LANG

This will probably show that your shell is not using a utf-8 locale.

Hexadecimal value 0x00 is a invalid character

To add to Sonz's answer above, following worked for us.

//Instead of 
XmlString.Replace("&#x0;", "[0x00]");
// use this
XmlString.Replace("\x00", "[0x00]");

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

How can I make IntelliJ IDEA update my dependencies from Maven?

File>Settings>Build,Execution,Deployment>Maven> Check : Always update snapshot

That worked for me.

PostgreSQL database service

The solution was simply to comment the lines "work_mem=256MB" and "maintenance_work_mem=$3GB" in the file postgresql.conf and try to start the postgresql service. (start -> run -> services.msc) and look for the postgresql-[version] service then right click and start.

How do I rename a local Git branch?

All of the previous answers are talking about git branch -m. Of course, it's easy to operate, but for me, it may be a little hard to remember another Git command. So I tried to get the work done by the command I was familiar with. Yeah, you may guessed it.

I use git branch -b <new_branch_name>. And if you don't want to save the old branch now you can execute git branch -D <old_branch_name> to remove it.

I know it may be a little tedious, but it's easier to understand and remember. I hope it‘s helpful for you.

What does request.getParameter return?

String onevalue;   
if(request.getParameterMap().containsKey("one")!=false) 
{
onevalue=request.getParameter("one").toString();
}

How to grep, excluding some patterns?

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

javascript, is there an isObject function like isArray?

use the following

It will return a true or false

theObject instanceof Object

How to get the background color code of an element in hex?

This Solution utilizes part of what @Newred and @Radu Di?a said. But will work in less standard cases.

 $(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');

The issue both of them have is that neither check for a space between background-color: and the color.

All of these will match with the above code.

 background-color: #ffffff
 background-color:      #fffff;
 background-color:#fffff;

Where are the python modules stored?

  1. You can iterate through directories listed in sys.path to find all modules (except builtin ones).
  2. It'll probably be somewhere around /usr/lib/pythonX.X/site-packages (again, see sys.path). And consider using native Python package management (via pip or easy_install, plus yolk) instead, packages in Linux distros-maintained repositories tend to be outdated.

Set android shape color programmatically

My Kotlin extension function version based on answers above with Compat:

fun Drawable.overrideColor_Ext(context: Context, colorInt: Int) {
    val muted = this.mutate()
    when (muted) {
        is GradientDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
        is ShapeDrawable -> muted.paint.setColor(ContextCompat.getColor(context, colorInt))
        is ColorDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
        else -> Log.d("Tag", "Not a valid background type")
    }
}

How to do case insensitive search in Vim

You can set ignorecase by default, run this in shell

echo "set ic" >> ~/.vimrc

Data binding for TextBox

We can use following code

textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

Where

  • "Text" – the property of textbox
  • model – the model object enter code here
  • "Name" – the value of model which to bind the textbox.

JQuery/Javascript: check if var exists

You can use typeof:

if (typeof pagetype === 'undefined') {
    // pagetype doesn't exist
}

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Calculating arithmetic mean (one type of average) in Python

I always supposed avg is omitted from the builtins/stdlib because it is as simple as

sum(L)/len(L) # L is some list

and any caveats would be addressed in caller code for local usage already.

Notable caveats:

  1. non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L) or from __future__ import division

  2. division by zero: the list may be empty. to resolve:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    

How to plot vectors in python using matplotlib

All nice solutions, borrowing and improvising for special case -> If you want to add a label near the arrowhead:


    arr = [2,3]
    txt = “Vector X”
    ax.annotate(txt, arr)
    ax.arrow(0, 0, *arr, head_width=0.05, head_length=0.1)

File size exceeds configured limit (2560000), code insight features not available

Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.

MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents] 

Idea.max.intellisense.filesize=999999 

WINDOWS: IDE_HOME\bin\idea.properties

How do I purge a linux mail box with huge number of emails?

alternative way:

mail -N
d *
quit

-N Inhibits the initial display of message headers when reading mail or editing a mail folder.
d * delete all mails

In Python, how do you convert a `datetime` object to seconds?

The standard way to find the processing time in ms of a block of code in python 3.x is the following:

import datetime

t_start = datetime.datetime.now()

# Here is the python3 code, you want 
# to check the processing time of

t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")

java.time.format.DateTimeParseException: Text could not be parsed at index 21

If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT (implicitly):

final Instant parsed = Instant.parse(dateTime);

If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME:

DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);

If neither is the case, you can construct a DateTimeFormatter in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME is constructed.


Your current pattern has several problems:

  • not using strict mode (ResolverStyle.STRICT);
  • using yyyy instead of uuuu (yyyy will not work in strict mode);
  • using 12-hour hh instead of 24-hour HH;
  • using only one digit S for fractional seconds, but input has three.

JavaScript ternary operator example with functions

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...

x = (1 < 2) ? true : false;

The use of ternary here is totally unnecessary - you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

Apply formula to the entire column

Let's say you want to substitute something in an array of string and you don't want to perform the copy-paste on your entire sheet.

Let's take this as an example:

  • String array in column "A": {apple, banana, orange, ..., avocado}
  • You want to substitute the char of "a" to "x" to have: {xpple, bxnxnx, orxnge, ..., xvocado}

To apply this formula on the entire column (array) in a clean an elegant way, you can do:

=ARRAYFORMULA(SUBSTITUE(A:A, "a", "x"))

It works for 2D-arrays as well, let's say:

=ARRAYFORMULA(SUBSTITUE(A2:D83, "a", "x"))

Correct Way to Load Assembly, Find Class and Call Run() Method

When you build your assembly, you can call AssemblyBuilder.SetEntryPoint, and then get it back from the Assembly.EntryPoint property to invoke it.

Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main:

static void Run(string[] args)

How can I check whether a variable is defined in Node.js?

If your variable is not declared nor defined:

if ( typeof query !== 'undefined' ) { ... }

If your variable is declared but undefined. (assuming the case here is that the variable might not be defined but it can be any other falsy value like false or "")

if ( query ) { ... }

If your variable is declared but can be undefined or null:

if ( query != null ) { ... } // undefined == null

Highlighting Text Color using Html.fromHtml() in Android?

To make part of your text underlined and colored

in your strings.xml

<string name="text_with_colored_underline">put the text here and &lt;u>&lt;font color="#your_hexa_color">the underlined colored part here&lt;font>&lt;u></string>

then in the activity

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));

and for clickable links:

<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>

and in your activity:

yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I know this has been already answered a long time ago but the answer didnt fix it for me but, I just removed everything from the sources in the buildpath settings and re-added them

counting number of directories in a specific directory

Best way to do it:

ls -la | grep -v total | wc -l

This gives you the perfect count.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Android studio Gradle build speed up

There is a newer version of gradle (ver 2.4).

You can set this for your project(s) by opening up 'Project Structure' dialog from File menu,

Project Structure -> Project -> Gradle version

and set it to '2.4'.
You can read more about boosting performance at this link.

How can I inspect element in chrome when right click is disabled?

CTRL+SHIFT+I brings up the developers tools.

check if jquery has been loaded, then load it if false

Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.

<script type="text/javascript">
if (typeof jQuery == 'undefined') {
  document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');        
  } 
</script>

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>

Remove specific commit

The algorithm that Git uses when calculating diff's to be reverted requires that

  1. the lines being reverted are not modified by any later commits.
  2. that there not be any other "adjacent" commits later in the history.

The definition of "adjacent" is based on the default number of lines from a context diff, which is 3. So if 'myfile' was constructed like this:

$ cat >myfile <<EOF
line 1
junk
junk
junk
junk
line 2
junk
junk
junk
junk
line 3
EOF
$ git add myfile
$ git commit -m "initial check-in"
 1 files changed, 11 insertions(+), 0 deletions(-)
 create mode 100644 myfile

$ perl -p -i -e 's/line 2/this is the second line/;' myfile
$ git commit -am "changed line 2 to second line"
[master d6cbb19] changed line 2
 1 files changed, 1 insertions(+), 1 deletions(-)

$ perl -p -i -e 's/line 3/this is the third line/;' myfile
$ git commit -am "changed line 3 to third line"
[master dd054fe] changed line 3
 1 files changed, 1 insertions(+), 1 deletions(-)

$ git revert d6cbb19
Finished one revert.
[master 2db5c47] Revert "changed line 2"
 1 files changed, 1 insertions(+), 1 deletions(-)

Then it all works as expected.

The second answer was very interesting. There is a feature which has not yet been officially released (though it is available in Git v1.7.2-rc2) called Revert Strategy. You can invoke git like this:

git revert --strategy resolve <commit>

and it should do a better job figuring out what you meant. I do not know what the list of available strategies is, nor do I know the definition of any strategy.

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

How to set recurring schedule for xlsm file using Windows Task Scheduler

Three important steps - How to Task Schedule an excel.xls(m) file

simply:

  1. make sure the .vbs file is correct
  2. set the Action tab correctly in Task Scheduler
  3. don't turn on "Run whether user is logged on or not"

IN MORE DETAIL...

  1. Here is an example .vbs file:

`

'   a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt  to .vbs

'Write Excel.xls  Sheet's full path here
strPath = "C:\RodsData.xlsm" 

'Write the macro name - could try including module name
strMacro = "Update" '    "Sheet1.Macro2" 

'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application") 
objApp.Visible = True   '   or False 

'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath) 
objApp.Run strMacro     '   wbToRun.Name & "!" & strMacro 
wbToRun.Save 
wbToRun.Close 
objApp.Quit 

'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!",         vbInformation 
'

`

  1. In the Action tab (Task Scheduler):

set Program/script: = C:\Windows\System32\cscript.exe

set Add arguments (optional): = C:\MyVbsFile.vbs

  1. Finally, don't turn on "Run whether user is logged on or not".

That should work.

Let me know!

Rod Bowen

How can I close a browser window without receiving the "Do you want to close this window" prompt?

Place the following code in the ASPX.

<script language=javascript>
function CloseWindow() 
{
    window.open('', '_self', '');
    window.close();
}
</script>

Place the following code in the code behind button click event.

string myclosescript = "<script language='javascript' type='text/javascript'>CloseWindow();</script>";

Page.ClientScript.RegisterStartupScript(GetType(), "myclosescript", myclosescript);

If you dont have any processing before close then you can directly put the following code in the ASPX itself in the button click tag.

OnClientClick="CloseWindow();"

Hope this helps.

jQuery ajax request with json response, how to?

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

see https://github.com/ArtNazarov/LazyJs

Sorry for my bad English

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

In my case I also have unmanaged dll's (C++) in workspace and if you specify:

<files>
    <file src="bin\*.dll" target="lib" />
</files>

nuget would try to load every dll as an assembly, even the C++ libraries! To avoid this behaviour explicitly define your C# assemblies with references tag:

<references>
    <reference file="Managed1.dll" />
    <reference file="Managed2.dll" />
</references>

Remark: parent of references is metadata -> according to documentation https://docs.microsoft.com/en-us/nuget/reference/nuspec#general-form-and-schema

Documentation: https://docs.microsoft.com/en-us/nuget/reference/nuspec

How to get ip address of a server on Centos 7 in bash

Enter the command ip addr at the console

enter image description here

Difference between DOM parentNode and parentElement

there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.

Google Chrome forcing download of "f.txt" file

FYI, after reading this thread, I took a look at my installed programs and found that somehow, shortly after upgrading to Windows 10 (possibly/probably? unrelated), an ASK search app was installed as well as a Chrome extension (Windows was kind enough to remind to check that). Since removing, I have not have the f.txt issue.

Proper way of checking if row exists in table in PL/SQL block

If you are using an explicit cursor, It should be as follows.

DECLARE
   CURSOR get_id IS 
    SELECT id 
      FROM person 
      WHERE id = 10;

  id_value_ person.id%ROWTYPE;
BEGIN 
   OPEN get_id;
   FETCH get_id INTO id_value_;

   IF (get_id%FOUND) THEN
     DBMS_OUTPUT.PUT_LINE('Record Found.');
   ELSE
     DBMS_OUTPUT.PUT_LINE('Record Not Found.');
   END IF;
   CLOSE get_id;

EXCEPTION
  WHEN no_data_found THEN
  --do things when record doesn't exist
END;

What's the difference between Sender, From and Return-Path?

A minor update to this: a sender should never set the Return-Path: header. There's no such thing as a Return-Path: header for a message in transit. That header is set by the MTA that makes final delivery, and is generally set to the value of the 5321.From unless the local system needs some kind of quirky routing.

It's a common misunderstanding because users rarely see an email without a Return-Path: header in their mailboxes. This is because they always see delivered messages, but an MTA should never see a Return-Path: header on a message in transit. See http://tools.ietf.org/html/rfc5321#section-4.4

Java/ JUnit - AssertTrue vs AssertFalse

Your first reaction to these methods is quite interesting to me. I will use it in future arguments that both assertTrue and assertFalse are not the most friendly tools. If you would use

assertThat(thisOrThat, is(false));

it is much more readable, and it prints a better error message too.

How to open the second form?

I assume your talking about windows forms:

To display your form use the Show() method:

Form form2 = new Form();
form2.Show();

to close the form use Close():

form2.Close();

How to insert text into the textarea at the current cursor position?

This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/

$('input[type=button]').on('click', function() {
    var cursorPos = $('#text').prop('selectionStart');
    var v = $('#text').val();
    var textBefore = v.substring(0,  cursorPos);
    var textAfter  = v.substring(cursorPos, v.length);

    $('#text').val(textBefore + $(this).val() + textAfter);
});

How can I rotate an HTML <div> 90 degrees?

you can use css3 property writing-mode writing-mode: tb-rl

css-tricks

mozilla

Changing tab bar item image and text color iOS

Swift 3

This worked for me (referring to set tabBarItems image colors):

UITabBar.appearance().tintColor = ThemeColor.Blue

if let items = tabBarController.tabBar.items {
        let tabBarImages = getTabBarImages() // tabBarImages: [UIImage]
        for i in 0..<items.count {
            let tabBarItem = items[i]
            let tabBarImage = tabBarImages[i]
            tabBarItem.image = tabBarImage.withRenderingMode(.alwaysOriginal)
            tabBarItem.selectedImage = tabBarImage
        }
    }

I have noticed that if you set image with rendering mode = .alwaysOriginal, the UITabBar.tintColor doesn't have any effect.

How to validate an email address using a regular expression?

I used

/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$/

which includes the capitalized letter as well. You wouldn't even need to use tolowercase in this case.

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

How does bitshifting work in Java?

public class Shift {
 public static void main(String[] args) {
  Byte b = Byte.parseByte("00101011",2);
  System.out.println(b);
  byte val = b.byteValue();
  Byte shifted = new Byte((byte) (val >> 2));
  System.out.println(shifted);

  // often overloked  are the methods of Integer

  int i = Integer.parseInt("00101011",2);
  System.out.println( Integer.toBinaryString(i));
  i >>= 2;
  System.out.println( Integer.toBinaryString(i));
 }
}

Output:

43
10
101011
1010

How to convert any date format to yyyy-MM-dd

string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true); 
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);

These Links might also Help you

DateTime.ToString() Patterns

String Format for DateTime [C#]

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

How to ignore HTML element from tabindex?

Just add the attribute disabled to the element (or use jQuery to do it for you). Disabled prevents the input from being focused or selected at all.

Script Tag - async & defer

HTML5: async, defer

In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.

  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.

  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

In MySQL, how to copy the content of one table to another table within the same database?

This worked for me,

CREATE TABLE newtable LIKE oldtable;

Replicates newtable with old table

INSERT newtable SELECT * FROM oldtable;

Copies all the row data to new table.

Thank you

adb command not found

+ The reason is: you are in the wrong directory (means it doesn't contain adb executor).

+ The solution is (step by step):

1) Find where the adb was installed. Depend on what OS you are using.

Mac, it could be in: "~/Library/Android/sdk/platform-tools"

or

Window, it could be in: "%USERPROFILE%\AppData\Local\Android\sdk\platform-tools\".

However, in case you could NOT remember this such long directory, you can quickly find it by the command "find". Try this in your terminal/ command line, "find / -name "platform-tools" 2> /dev/null" (Note: I didn't test in Window yet, but it works with Mac for sure).

*Explain the find command,

  • Please note there is a space before the "/" character --> only find in User directory not all the computer.
  • "2> /dev/null" --> ignore find results denied by permission. Try the one without this code, you will understand what I mean.

2) Go to where we installed adb. There are 3 ways mentioned by many people:

  • Change the PATH global param (which I won't recommend) by: "export PATH=~/Library/Android/sdk/platform-tools" which is the directory you got from above. Note, this command won't print any result, if you want to make sure you changed PATH successfully, call "export | grep PATH" to see what the PATH is.

  • Add more definition for the PATH global param (which I recommend) by: "export PATH=~/Library/Android/sdk/platform-tools:$PATH" or "export PATH=$PATH:~/Library/Android/sdk/platform-tools"

  • Go to the path we found above by "cd ~/Library/Android/sdk/platform-tools"

3) Use adb:

  • If you change or update the PATH, simply call any adb functions, since you added the PATH as a global param. (e.g: "adb devices")

  • If you go to the PATH by cd command, call adb functions with pre-fix "./ " (e.g: "./ adb devices")

Eclipse count lines of code

The first thing to do is to determine your definition of "line of code" (LOC). In both your question

It counts a line with just one } as a line and he doesn't want that to count as "its not a line, its a style choice"

and in the answers, e.g.,

You can adjust the Lines of Code metrics by ignoring blank and comment-only lines or exclude Javadoc if you want

you can tell that people have different opinions as to what constitutes a line of code. In particular, people are often imprecise about whether they really want the number of lines of code or the number of statements. For example, if you have the following really long line filled with statements, what do you want to report, 1 LOC or hundreds of statements?

{ a = 1; b = 2; if (a==c) b++; /* etc. for another 1000 characters */ }

And when somebody asks you what you are calling a LOC, make sure you can answer, even if it is just "my definition of a LOC is Metrics2's definition". In general, for most commonly formatted code (unlike my example), the popular tools will give numbers fairly similar, so Metrics2, SonarQube, etc. should all be fine, as long as you use them consistently. In other words, don't count the LOC of some code using one tool and compare that value to a later version of that code that was measured with a different tool.

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Passing two command parameters using a WPF binding

If your values are static, you can use x:Array:

<Button Command="{Binding MyCommand}">10
  <Button.CommandParameter>
    <x:Array Type="system:Object">
       <system:String>Y</system:String>
       <system:Double>10</system:Double>
    </x:Array>
  </Button.CommandParameter>
</Button>

Counting repeated elements in an integer array

public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;

    public static void main(String[] args) {
        int n, num;
        sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n =sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++){
            System.out.print("Enter the element at position "+i+": ");
            num = sc.nextInt();
            a[enter image description here][1][i]=num;
        }
        System.out.print("Elements in array are: ");
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+" ");
        System.out.println();
        duplicate(a);
        System.out.println("There are "+totalCount+" repeated numbers:");
    }

    public static void duplicate(int[] a){
        int j = 0,count, recount, temp;
        for(int i=0; i<a.length;i++){
            count = 0;
            recount = 0;
            j=i+1;
            while(j<a.length){
                if(a[i]==a[j])
                    count++;
                j++;
            }
            if(count>0){
                temp = a[i];
                for(int x=0;x<i;x++){
                    if(a[x]==temp)
                        recount++;
                }
                if(recount==0){                 
                    totalCount++;
                    System.out.println(+a[i]+" : "+count+" times");
                }   
            }

        }
    }

}

regular expression for Indian mobile numbers

/(((^[\+,0][9][1])(((\s[0-9]{7,10})|(\S[0-9]{7,10}))|([-]\S[0-9]{7,10})))|((^[\+,0][2]{2,2})((\S[0-9]{7,8})|((([-])[0-9]{7,8})|(\s[0-9]{7,8})))))|(((^[6,7,8,9][0-9]{9,9}))|(^[0,\+](([9][1)|[6,7,8,9]))[0-9]{8,9}))/gm

I don't know if there is a simple expression for this but I have created this REGEX that validates all possible Indian numbers that contains (0 or +) then (91 or 22 (since I needed it for Maharashtra and second thing is that India have too many STD codes)) or directly searches for numbers starting with 6,7,8,9 that have/don't have a 0 in front of it .

(/[regex]/gm) is a trial for multi-line search you can remove it(//gm) if it fails to work/gives error.

Feel free to try it at regex101. My Project of this REGEX is here .

adding to window.onload event?

There are basically two ways

  1. store the previous value of window.onload so your code can call a previous handler if present before or after your code executes

  2. using the addEventListener approach (that of course Microsoft doesn't like and requires you to use another different name).

The second method will give you a bit more safety if another script wants to use window.onload and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.

Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.

Get total number of items on Json object?

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

gridview data export to excel in asp.net

Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.

How to run binary file in Linux

:-) If not typo, why are you using ./commonRT instead of ./commonKT ??

How to convert strings into integers in Python?

I would rather prefer using only comprehension lists:

[[int(y) for y in x] for x in T1]

Encoding URL query parameters in Java

The built in Java URLEncoder is doing what it's supposed to, and you should use it.

A "+" or "%20" are both valid replacements for a space character in a URL. Either one will work.

A ":" should be encoded, as it's a separator character. i.e. http://foo or ftp://bar. The fact that a particular browser can handle it when it's not encoded doesn't make it correct. You should encode them.

As a matter of good practice, be sure to use the method that takes a character encoding parameter. UTF-8 is generally used there, but you should supply it explicitly.

URLEncoder.encode(yourUrl, "UTF-8");

How can I get Git to follow symlinks?

What I did to add to get the files within a symlink into Git (I didn't use a symlink but):

sudo mount --bind SOURCEDIRECTORY TARGETDIRECTORY

Do this command in the Git-managed directory. TARGETDIRECTORY has to be created before the SOURCEDIRECTORY is mounted into it.

It works fine on Linux, but not on OS X! That trick helped me with Subversion too. I use it to include files from an Dropbox account, where a webdesigner does his/her stuff.

How can I list all tags for a Docker image on a remote registry?

The Docker V2 API requires an OAuth bearer token with the appropriate claims. In my opinion, the official documentation is rather vague on the topic. So that others don't go through the same pain I did, I offer the below docker-tags function.

The most recent version of docker-tags can be found in my GitHubGist : "List Docker Image Tags using bash".

The docker-tags function has a dependency on jq. If you're playing with JSON, you likely already have it.

#!/usr/bin/env bash
docker-tags() {
    arr=("$@")

    for item in "${arr[@]}";
    do
        tokenUri="https://auth.docker.io/token"
        data=("service=registry.docker.io" "scope=repository:$item:pull")
        token="$(curl --silent --get --data-urlencode ${data[0]} --data-urlencode ${data[1]} $tokenUri | jq --raw-output '.token')"
        listUri="https://registry-1.docker.io/v2/$item/tags/list"
        authz="Authorization: Bearer $token"
        result="$(curl --silent --get -H "Accept: application/json" -H "Authorization: Bearer $token" $listUri | jq --raw-output '.')"
        echo $result
    done
}

Example

docker-tags "microsoft/nanoserver" "microsoft/dotnet" "library/mongo" "library/redis"

Admittedly, docker-tags makes several assumptions. Specifically, the OAuth request parameters are mostly hard coded. A more ambitious implementation would make an unauthenticated request to the registry and derive the OAuth parameters from the unauthenticated response.

Selectors in Objective-C?

As per apple docs: https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn’t do anything. It simply identifies a method. The only thing that makes the selector method name different from a plain string is that the compiler makes sure that selectors are unique. What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with. Suppose you had a selector for the method run, and classes Dog, Athlete, and ComputerSimulation (each of which implemented a method run). The selector could be used with an instance of each of the classes to invoke its run method—even though the implementation might be different for each.

Example: (lldb) breakpoint --set selector viewDidLoad

This will set a breakpoint on all viewDidLoad implementations in your app. So selector is kind of a global identifier for a method.

How do I expire a PHP session after 30 minutes?

This post shows a couple of ways of controlling the session timeout: http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions

IMHO the second option is a nice solution:

<?php
/***
 * Starts a session with a specific timeout and a specific GC probability.
 * @param int $timeout The number of seconds until it should time out.
 * @param int $probability The probablity, in int percentage, that the garbage 
 *        collection routine will be triggered right now.
 * @param strint $cookie_domain The domain path for the cookie.
 */
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
    // Set the max lifetime
    ini_set("session.gc_maxlifetime", $timeout);

    // Set the session cookie to timout
    ini_set("session.cookie_lifetime", $timeout);

    // Change the save path. Sessions stored in teh same path
    // all share the same lifetime; the lowest lifetime will be
    // used for all. Therefore, for this to work, the session
    // must be stored in a directory where only sessions sharing
    // it's lifetime are. Best to just dynamically create on.
    $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
    $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
    if(!file_exists($path)) {
        if(!mkdir($path, 600)) {
            trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
        }
    }
    ini_set("session.save_path", $path);

    // Set the chance to trigger the garbage collection.
    ini_set("session.gc_probability", $probability);
    ini_set("session.gc_divisor", 100); // Should always be 100

    // Start the session!
    session_start();

    // Renew the time left until this session times out.
    // If you skip this, the session will time out based
    // on the time when it was created, rather than when
    // it was last used.
    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
    }
}