Programs & Examples On #Suid

What are metaclasses in Python?

The type() function can return the type of an object or create a new type,

for example, we can create a Hi class with the type() function and do not need to use this way with class Hi(object):

def func(self, name='mike'):
    print('Hi, %s.' % name)

Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.

type(Hi)
type

type(h)
__main__.Hi

In addition to using type() to create classes dynamically, you can control creation behavior of class and use metaclass.

According to the Python object model, the class is the object, so the class must be an instance of another certain class. By default, a Python class is instance of the type class. That is, type is metaclass of most of the built-in classes and metaclass of user-defined classes.

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

class CustomList(list, metaclass=ListMetaclass):
    pass

lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')

lst
['custom_list_1', 'custom_list_2']

Magic will take effect when we passed keyword arguments in metaclass, it indicates the Python interpreter to create the CustomList through ListMetaclass. new (), at this point, we can modify the class definition, for example, and add a new method and then return the revised definition.

Auto increment primary key in SQL Server Management Studio 2012

You have to expand the Identity section to expose increment and seed.

enter image description here

Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer

What's the best practice to round a float to 2 decimals?

Here is a simple one-line solution

((int) ((value + 0.005f) * 100)) / 100f

pthread_join() and pthread_exit()

In pthread_exit, ret is an input parameter. You are simply passing the address of a variable to the function.

In pthread_join, ret is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL.

Long explanation:

In pthread_join, you get back the address passed to pthread_exit by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.

Printing reverse of any String without using any predefined function?

It is very simple using while loop

public class Test {
public static void main(String[] args) {
    String name = "subha chandra";
    int len = name.length();
    while(len > 0){
        len--;
        char c = name.charAt(len);
        System.out.print(c); // use String.valueOf(c) to convert char to String
    }
}    
}

Comparing two byte arrays in .NET

For comparing short byte arrays the following is an interesting hack:

if(myByteArray1.Length != myByteArray2.Length) return false;
if(myByteArray1.Length == 8)
   return BitConverter.ToInt64(myByteArray1, 0) == BitConverter.ToInt64(myByteArray2, 0); 
else if(myByteArray.Length == 4)
   return BitConverter.ToInt32(myByteArray2, 0) == BitConverter.ToInt32(myByteArray2, 0); 

Then I would probably fall out to the solution listed in the question.

It'd be interesting to do a performance analysis of this code.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

Simple PHP solution to this:

if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}

As the page is reloaded it will update on screen the new data and clear the $_POST ;)

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

To answer the title of the question (but not the question about the output you're getting):

Copying the following folder from your dev machine to your build server fixes this if it's just web applications

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications

Remove x86 according to how your build breaks. If you have other project types you will probably need to copy the entire msbuild folder.

Free Online Team Foundation Server

You can use Visual Studio Team Services for free. Also you can import a TFS repo to this cloud space.

Determine the data types of a data frame's columns

Another option is using the map function of the purrr package.

library(purrr)
map(df,class)

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

Back button and refreshing previous activity

in main:

@Override
public void onRestart()
{
    super.onRestart();
    finish();
    startActivity(getIntent());
}

Why does "return list.sort()" return None, not the list?

list.sort sorts the list in place, i.e. it doesn't return a new list. Just write

newList.sort()
return newList

How to find distinct rows with field in list using JPA and Spring?

I finally was able to figure out a simple solution without the @Query annotation.

List<People> findDistinctByNameNotIn(List<String> names);

Of course, I got the people object instead of only Strings. I can then do the change in java.

MySQL "Or" Condition

try this

mysql_query("
SELECT * FROM Drinks WHERE
    email='$Email'
    AND date='$Date_Today'
    OR date='$Date_Yesterday', '$Date_TwoDaysAgo', '$Date_ThreeDaysAgo', '$Date_FourDaysAgo', '$Date_FiveDaysAgo', '$Date_SixDaysAgo', '$Date_SevenDaysAgo'"     
   );

my be like this

 OR date='$Date_Yesterday' oR '$Date_TwoDaysAgo'.........

How do I iterate and modify Java Sets?

You could create a mutable wrapper of the primitive int and create a Set of those:

class MutableInteger
{
    private int value;
    public int getValue()
    {
        return value;
    }
    public void setValue(int value)
    {
        this.value = value;
    }
}

class Test
{
    public static void main(String[] args)
    {
        Set<MutableInteger> mySet = new HashSet<MutableInteger>();
        // populate the set
        // ....

        for (MutableInteger integer: mySet)
        {
            integer.setValue(integer.getValue() + 1);
        }
    }
}

Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

How do I use InputFilter to limit characters in an EditText in Android?

You can specify wanted characters in a regex and use it in InputFilter:

val regex = Regex("[a-zA-Z\\d ]")
    
editText.filters = arrayOf(InputFilter { source, _, _, _, _, _ ->
    source.filter { regex.matches(it.toString()) }
})

Notice, I didn't used \w character class, because it includes underscore _

How to sort alphabetically while ignoring case sensitive?

Collections.sort() lets you pass a custom comparator for ordering. For case insensitive ordering String class provides a static final comparator called CASE_INSENSITIVE_ORDER.

So in your case all that's needed is:

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);

How to Customize a Progress Bar In Android

There are two types of progress bars called determinate progress bar (fixed duration) and indeterminate progress bar (unknown duration).

Drawables for both of types of progress bar can be customized by defining drawable as xml resource. You can find more information about progress bar styles and customization at http://www.zoftino.com/android-progressbar-and-custom-progressbar-examples.

Customizing fixed or horizontal progress bar :

Below xml is a drawable resource for horizontal progress bar customization.

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
        android:gravity="center_vertical|fill_horizontal">
        <shape android:shape="rectangle"
            android:tint="?attr/colorControlNormal">
            <corners android:radius="8dp"/>
            <size android:height="20dp" />
            <solid android:color="#90caf9" />
        </shape>
    </item>
    <item android:id="@android:id/progress"
        android:gravity="center_vertical|fill_horizontal">
        <scale android:scaleWidth="100%">
            <shape android:shape="rectangle"
                android:tint="?attr/colorControlActivated">
                <corners android:radius="8dp"/>
                <size android:height="20dp" />
                <solid android:color="#b9f6ca" />
            </shape>
        </scale>
    </item>
</layer-list>

Customizing indeterminate progress bar

Below xml is a drawable resource for circular progress bar customization.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/progress"
        android:top="16dp"
        android:bottom="16dp">
                <rotate
                    android:fromDegrees="45"
                    android:pivotX="50%"
                    android:pivotY="50%"
                    android:toDegrees="315">
                    <shape android:shape="rectangle">
                        <size
                            android:width="80dp"
                            android:height="80dp" />
                        <stroke
                            android:width="6dp"
                            android:color="#b71c1c" />
                    </shape>
                </rotate>           
    </item>
</layer-list>

jQuery detect if textarea is empty

This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.

 var txt_msg = $("textarea").val();

 if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
    return false;
  }

How to keep a Python script output window open?

A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.

Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...

No changes required to any Python scripts.

I can still open a console window and specify python myscript.py if I want to...

(I just noticed @maurizio already posted this exact answer)

Defining a variable with or without export

By default, variables created within a script are only available to the current shell; child processes (sub-shells) will not have access to values that have been set or modified. Allowing child processes to see the values, requires use of the export command.

Is there a function in python to split a word into a list?

text = "just trying out"

word_list = []

for i in range(0, len(text)):
    word_list.append(text[i])
    i+=1

print(word_list)

['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

How to run Tensorflow on CPU

In some systems one have to specify:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"

BEFORE importing tensorflow.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.

ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;

How to find current transaction level?

Run this:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncommitted' 
WHEN 2 THEN 'ReadCommitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL 
FROM sys.dm_exec_sessions 
where session_id = @@SPID

docs.microsoft.com reference for the constant values.

How to check if any value is NaN in a Pandas DataFrame

Just using math.isnan(x), Return True if x is a NaN (not a number), and False otherwise.

How to split a single column values to multiple column values?

Here is how I did this on a SQLite database:

SELECT SUBSTR(name, 1,INSTR(name, " ")-1) as Firstname,
SUBSTR(name, INSTR(name," ")+1, LENGTH(name)) as Lastname
FROM YourTable;

Hope it helps.

PHP error: Notice: Undefined index:

How I can get rid of it so it doesnt display it?

People here are trying to tell you that it's unprofessional (and it is), but in your case you should simply add following to the start of your application:

 error_reporting(E_ERROR|E_WARNING);

This will disable E_NOTICE reporting. E_NOTICES are not errors, but notices, as the name says. You'd better check this stuff out and proof that undefined variables don't lead to errors. But the common case is that they are just informal, and perfectly normal for handling form input with PHP.

Also, next time Google the error message first.

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

How can I let a table's body scroll but keep its head fixed in place?

Edit:   This is a very old answer and is here for prosperity just to show that it was supported once back in the 2000's but dropped because browsers strategy in the 2010's was to respect W3C specifications even if some features were removed: Scrollable table with fixed header/footer was clumsily specified before HTML5.


Bad news

Unfortunately there is no elegant way to handle scrollable table with fixed thead/tfoot because HTML/CSS specifications are not very clear about that feature.

Explanations

Although HTML 4.01 Specification says thead/tfoot/tbody are used (introduced?) to scroll table body:

Table rows may be grouped [...] using the THEAD, TFOOT and TBODY elements [...]. This division enables user agents to support scrolling of table bodies independently of the table head and foot.

But the working scrollable table feature on FF 3.6 has been removed in FF 3.7 because considered as a bug because not compliant with HTML/CSS specifications. See this and that comments on FF bugs.

Mozilla Developer Network tip

Below is a simplified version of the MDN useful tips for scrollable table
see this archived page or the current French version

<style type="text/css">
table {
  border-spacing: 0;              /* workaround */
}
tbody {
  height: 4em;                    /* define the height */
  overflow-x: hidden;             /* esthetics */
  overflow-y: auto;               /* allow scrolling cells */
}
td {
  border-left:   1px solid blue;  /* workaround */
  border-bottom: 1px solid blue;  /* workaround */
}
</style>

<table>
    <thead><tr><th>Header
    <tfoot><tr><th>Footer
    <tbody>
        <tr><td>Cell 1    <tr><td>Cell 2
        <tr><td>Cell 3    <tr><td>Cell 4
        <tr><td>Cell 5    <tr><td>Cell 6
        <tr><td>Cell 7    <tr><td>Cell 8
        <tr><td>Cell 9    <tr><td>Cell 10
        <tr><td>Cell 11   <tr><td>Cell 12
        <tr><td>Cell 13   <tr><td>Cell 14
    </tbody>
</table>

However MDN also says this does not work any more on FF :-(
I have also tested on IE8 => table is not scrollable either :-((

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Another option would be to add engine='python' to the command pandas.read_csv(filename, sep='\t', engine='python')

CSS: Control space between bullet and <li>

ul
{
list-style-position:inside;
} 

Definition and Usage

The list-style-position property specifies if the list-item markers should appear inside or outside the content flow.

Source: http://www.w3schools.com/cssref/pr_list-style-position.asp

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I haven't figure out the reason but reinstalling the .pfx certificate(both in current user and local machine) works for me.

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

PHP Redirect with POST data

I have another solution that makes this possible. It requires the client be running Javascript (which I think is a fair requirement these days).

Simply use an AJAX request on Page A to go and generate your invoice number and customer details in the background (your previous Page B), then once the request gets returned successfully with the correct information - simply complete the form submission over to your payment gateway (Page C).

This will achieve your result of the user only clicking one button and proceeding to the payment gateway. Below is some pseudocode

HTML:

<form id="paymentForm" method="post" action="https://example.com">
  <input type="hidden" id="customInvoiceId" .... />
  <input type="hidden" .... />

  <input type="submit" id="submitButton" />
</form>

JS (using jQuery for convenience but trivial to make pure Javascript):

$('#submitButton').click(function(e) {
  e.preventDefault(); //This will prevent form from submitting

  //Do some stuff like build a list of things being purchased and customer details

  $.getJSON('setupOrder.php', {listOfProducts: products, customerDetails: details }, function(data) {
  if (!data.error) {
    $('#paymentForm #customInvoiceID').val(data.id);
    $('#paymentForm').submit();   //Send client to the payment processor
  }
});

Data binding in React

To bind a control to your state you need to call a function on the component that updates the state from the control's event handler.

Rather than have an update function for all your form fields, you could create a generic update function using ES6 computed name feature and pass it the values it needs inline from the control like this:

_x000D_
_x000D_
class LovelyForm extends React.Component {_x000D_
  constructor(props) {_x000D_
  alert("Construct");_x000D_
    super(props);_x000D_
    this.state = {_x000D_
      field1: "Default 1",_x000D_
      field2: "Default 2"_x000D_
    };_x000D_
  }_x000D_
_x000D_
  update = (name, e) => {_x000D_
    this.setState({ [name]: e.target.value });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <form>_x000D_
        <p><input type="text" value={this.state.field1} onChange={(e) => this.update("field1", e)} />_x000D_
          {this.state.field1}</p>_x000D_
        <p><input type="text" value={this.state.field2} onChange={(e) => this.update("field2", e)} />_x000D_
          {this.state.field2}</p>_x000D_
      </form>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
ReactDOM.render(<LovelyForm/>, document.getElementById('example'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="example"></div>
_x000D_
_x000D_
_x000D_

MySQL match() against() - order by relevance and column?

I have never done so, but it seems like

MATCH (head, head, body) AGAINST ('some words' IN BOOLEAN MODE)

Should give a double weight to matches found in the head.


Just read this comment on the docs page, Thought it might be of value to you:

Posted by Patrick O'Lone on December 9 2002 6:51am

It should be noted in the documentation that IN BOOLEAN MODE will almost always return a relevance of 1.0. In order to get a relevance that is meaningful, you'll need to:

SELECT MATCH('Content') AGAINST ('keyword1 keyword2') as Relevance 
FROM table 
WHERE MATCH ('Content') AGAINST('+keyword1+keyword2' IN BOOLEAN MODE) 
HAVING Relevance > 0.2 
ORDER BY Relevance DESC 

Notice that you are doing a regular relevance query to obtain relevance factors combined with a WHERE clause that uses BOOLEAN MODE. The BOOLEAN MODE gives you the subset that fulfills the requirements of the BOOLEAN search, the relevance query fulfills the relevance factor, and the HAVING clause (in this case) ensures that the document is relevant to the search (i.e. documents that score less than 0.2 are considered irrelevant). This also allows you to order by relevance.

This may or may not be a bug in the way that IN BOOLEAN MODE operates, although the comments I've read on the mailing list suggest that IN BOOLEAN MODE's relevance ranking is not very complicated, thus lending itself poorly for actually providing relevant documents. BTW - I didn't notice a performance loss for doing this, since it appears MySQL only performs the FULLTEXT search once, even though the two MATCH clauses are different. Use EXPLAIN to prove this.

So it would seem you may not need to worry about calling the fulltext search twice, though you still should "use EXPLAIN to prove this"

Can I run a 64-bit VMware image on a 32-bit machine?

Yes, running a 64-bit OS in VMWare is possible from a 32-bit OS if you have a 64 bit processor.

I have an old Intel Core 2 Duo with Windows XP Professional 2002 running on it, and I got it to work.

First of all, see if your CPU is capable of running a 64-bit OS. Search for 'Processor check for 64-bit compatibility' on the VMware site. Run the program.

If it says your processor is capable, restart your computer and go into the BIOS and see if you have 'Virtualization' and are able to enable it. I was able to and got Windows Server 2008 R2 running under VMware on this old laptop.

I hope it works for you!

Python AttributeError: 'module' object has no attribute 'Serial'

I'm adding this solution for people who make the same mistake as I did.

In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.

Problem occurs when you import 'something' when your python file name is 'something.py'.

Object of class stdClass could not be converted to string

I use codeignator and I got the error:

Object of class stdClass could not be converted to string.

for this post I get my result

I use in my model section

$query = $this->db->get('user', 10);
        return $query->result();

and from this post I use

$query = $this->db->get('user', 10);
        return $query->row();

and I solved my problem

Add views in UIStackView programmatically

You have to set you distribution type. In your code, juste add:

self.stack1.distribution = UIStackViewDistributionFillEqually;

Or you can set the distribution directly in your interface builder. For example:

enter image description here

Hope that helps ;) Lapinou.

Sorting a Data Table

This was the shortest way I could find to sort a DataTable without having to create any new variables.

DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable

Where:

ASC - Ascending

DESC - Descending

ColumnName - The column you want to sort by

DataTable - The table you want to sort

Using GSON to parse a JSON array

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
    "number": "...",
    "title": ".." ,  //<- see that comma?
}

If you remove them your data will become

[
    {
        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"
    }
]

and

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

should work fine.

Convert an ArrayList to an object array

TypeA[] array = (TypeA[]) a.toArray();

SELECTING with multiple WHERE conditions on same column

AND will return you an answer only when both volunteer and uploaded are present in your column. Otherwise it will return null value...

try using OR in your statement ...

SELECT contactid  WHERE flag = 'Volunteer' OR flag = 'Uploaded'

Required maven dependencies for Apache POI to work

There are multiple jars which are required for your APACHE POI to work with your application.

List of JAR file:-

  1. poi-4.1.0
  2. poi-ooxml-4.1.0
  3. commons-collections4-4.3
  4. commons-compress-1.18
  5. xmlbeans-3.1.0
  6. poi-ooxml-schemas-3.9
  7. dom4j-1.6.1

Using IF ELSE statement based on Count to execute different Insert statements

Not very clear what you mean by

"I cant find any examples to help me understand how I can use this to run 2 different statements:"

. Is it using CASE like a SWITCH you are after?

select case when totalCount >= 0 and totalCount < 11 then '0-10'
            when tatalCount > 10 and totalCount < 101 then '10-100'
            else '>100' end as newColumn
from (
  SELECT [Some Column], COUNT(*) TotalCount
  FROM INCIDENTS
  WHERE [Some Column] = 'Target Data'
  GROUP BY [Some Column]
) A

Use awk to find average of a column

awk 's+=$2{print s/NR}' table | tail -1

I am using tail -1 to print the last line which should have the average number...

How do I activate a virtualenv inside PyCharm's terminal?

I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.

image

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Download multiple files as a zip-file using php

You are ready to do with php zip lib, and can use zend zip lib too,

<?PHP
// create object
$zip = new ZipArchive();   

// open archive 
if ($zip->open('app-0.09.zip') !== TRUE) {
    die ("Could not open archive");
}

// get number of files in archive
$numFiles = $zip->numFiles;

// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
    $file = $zip->statIndex($x);
    printf("%s (%d bytes)", $file['name'], $file['size']);
    print "
";    
}

// close archive
$zip->close();
?>

http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/

and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

Is there any use for unique_ptr with array?

There are tradeoffs, and you pick the solution which matches what you want. Off the top of my head:

Initial size

  • vector and unique_ptr<T[]> allow the size to be specified at run-time
  • array only allows the size to be specified at compile time

Resizing

  • array and unique_ptr<T[]> do not allow resizing
  • vector does

Storage

  • vector and unique_ptr<T[]> store the data outside the object (typically on the heap)
  • array stores the data directly in the object

Copying

  • array and vector allow copying
  • unique_ptr<T[]> does not allow copying

Swap/move

  • vector and unique_ptr<T[]> have O(1) time swap and move operations
  • array has O(n) time swap and move operations, where n is the number of elements in the array

Pointer/reference/iterator invalidation

  • array ensures pointers, references and iterators will never be invalidated while the object is live, even on swap()
  • unique_ptr<T[]> has no iterators; pointers and references are only invalidated by swap() while the object is live. (After swapping, pointers point into to the array that you swapped with, so they're still "valid" in that sense.)
  • vector may invalidate pointers, references and iterators on any reallocation (and provides some guarantees that reallocation can only happen on certain operations).

Compatibility with concepts and algorithms

  • array and vector are both Containers
  • unique_ptr<T[]> is not a Container

I do have to admit, this looks like an opportunity for some refactoring with policy-based design.

How to manage local vs production settings in Django?

Two Scoops of Django: Best Practices for Django 1.5 suggests using version control for your settings files and storing the files in a separate directory:

project/
    app1/
    app2/
    project/
        __init__.py
        settings/
            __init__.py
            base.py
            local.py
            production.py
    manage.py

The base.py file contains common settings (such as MEDIA_ROOT or ADMIN), while local.py and production.py have site-specific settings:

In the base file settings/base.py:

INSTALLED_APPS = (
    # common apps...
)

In the local development settings file settings/local.py:

from project.settings.base import *

DEBUG = True
INSTALLED_APPS += (
    'debug_toolbar', # and other apps for local development
)

In the file production settings file settings/production.py:

from project.settings.base import *

DEBUG = False
INSTALLED_APPS += (
    # other apps for production site
)

Then when you run django, you add the --settings option:

# Running django for local development
$ ./manage.py runserver 0:8000 --settings=project.settings.local

# Running django shell on the production site
$ ./manage.py shell --settings=project.settings.production

The authors of the book have also put up a sample project layout template on Github.

Pass props to parent component in React.js

Here is a simple 3 step ES6 implementation using function binding in the parent constructor. This is the first way the official react tutorial recommends (there is also public class fields syntax not covered here). You can find all of this information here https://reactjs.org/docs/handling-events.html

Binding Parent Functions so Children Can Call Them (And pass data up to the parent! :D )

  1. Make sure in the parent constructor you bind the function you created in the parent
  2. Pass the bound function down to the child as a prop (No lambda because we are passing a ref to function)
  3. Call the bound function from a child event (Lambda! We're calling the function when the event is fired. If we don't do this the function will automatically run on load and not be triggered on the event.)

Parent Function

handleFilterApply(filterVals){} 

Parent Constructor

this.handleFilterApply = this.handleFilterApply.bind(this);

Prop Passed to Child

onApplyClick = {this.handleFilterApply}

Child Event Call

onClick = {() => {props.onApplyClick(filterVals)}

How can I generate a list of consecutive numbers?

Just to give you another example, although range(value) is by far the best way to do this, this might help you later on something else.

list = []
calc = 0

while int(calc) < 9:
    list.append(calc)
    calc = int(calc) + 1

print list
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Posting parameters to a url using the POST method without using a form

If you're trying to link to something, rather than do it from code you can redirect your request through: http://getaspost.appspot.com/

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Change

CREATE DEFINER =  `root`@`localhost` FUNCTION  `fnc_calcWalkedDistance` (

By

FUNCTION  `fnc_calcWalkedDistance` (

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

You will need to have root access to do this. If you aren't already the administrative user, login as the administrator. Then use 'sudo' to change the permissions:

sudo chmod go-w /usr/local/bin

Obviously, that will mean you can no longer install material in /usr/local/bin except via 'sudo', but you probably shouldn't be doing that anyway.

How to _really_ programmatically change primary and accent color in Android Lollipop?

I used the Dahnark's code but I also need to change the ToolBar background:

if (dark_ui) {
    this.setTheme(R.style.Theme_Dark);

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
        getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
    }
} else {
    this.setTheme(R.style.Theme_Light);
}

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.app_bar);

if(dark_ui) {
    toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}

Randomize numbers with jQuery?

This doesn't require jQuery. The JavaScript Math.random function returns a random number between 0 and 1, so if you want a number between 1 and 6, you can do:

var number = 1 + Math.floor(Math.random() * 6);

Update: (as per comment) If you want to display a random number that changes every so often, you can use setInterval to create a timer:

setInterval(function() {
  var number = 1 + Math.floor(Math.random() * 6);
  $('#my_div').text(number);
},
1000); // every 1 second

Understanding the main method of python

If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

Git: How to remove file from index without deleting files from any repository

The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.

Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.

https://help.github.com/articles/remove-sensitive-data/

You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.

To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.

It looked intimidating at first, but really, was easy and worked like a charm ! :-)

Iterator Loop vs index loop

It always depends on what you need.

You should use operator[] when you need direct access to elements in the vector (when you need to index a specific element in the vector). There is nothing wrong in using it over iterators. However, you must decide for yourself which (operator[] or iterators) suits best your needs.

Using iterators would enable you to switch to other container types without much change in your code. In other words, using iterators would make your code more generic, and does not depend on a particular type of container.

Write a function that returns the longest palindrome in a given string

Reference: Wikipedia.com

The best algorithm i have ever found, with complexity O(N)

 import java.util.Arrays;

 public class ManachersAlgorithm {

  public static String findLongestPalindrome(String s) {
    if (s==null || s.length()==0)
      return "";

    char[] s2 = addBoundaries(s.toCharArray());
    int[] p = new int[s2.length]; 
    int c = 0, r = 0; // Here the first element in s2 has been processed.
    int m = 0, n = 0; // The walking indices to compare if two elements are the same
    for (int i = 1; i<s2.length; i++) {
      if (i>r) {
        p[i] = 0; m = i-1; n = i+1;
      } else {
        int i2 = c*2-i;
        if (p[i2]<(r-i)) {
          p[i] = p[i2];
          m = -1; // This signals bypassing the while loop below. 
        } else {
          p[i] = r-i;
          n = r+1; m = i*2-n;
        }
      }
      while (m>=0 && n<s2.length && s2[m]==s2[n]) {
        p[i]++; m--; n++;
      }
      if ((i+p[i])>r) {
        c = i; r = i+p[i];
      }
    }
    int len = 0; c = 0;
    for (int i = 1; i<s2.length; i++) {
      if (len<p[i]) {
        len = p[i]; c = i;
      }
    }
    char[] ss = Arrays.copyOfRange(s2, c-len, c+len+1);
    return String.valueOf(removeBoundaries(ss));
  }

  private static char[] addBoundaries(char[] cs) {
    if (cs==null || cs.length==0)
      return "||".toCharArray();

    char[] cs2 = new char[cs.length*2+1];
    for (int i = 0; i<(cs2.length-1); i = i+2) {
      cs2[i] = '|';
      cs2[i+1] = cs[i/2];
    }
    cs2[cs2.length-1] = '|';
    return cs2;
  }

  private static char[] removeBoundaries(char[] cs) {
    if (cs==null || cs.length<3)
      return "".toCharArray();

    char[] cs2 = new char[(cs.length-1)/2];
    for (int i = 0; i<cs2.length; i++) {
      cs2[i] = cs[i*2+1];
    }
    return cs2;
  }    
}

Read a file one line at a time in node.js?

I use below code the read lines after verify that its not a directory and its not included in the list of files need not to be check.

(function () {
  var fs = require('fs');
  var glob = require('glob-fs')();
  var path = require('path');
  var result = 0;
  var exclude = ['LICENSE',
    path.join('e2e', 'util', 'db-ca', 'someother-file'),
    path.join('src', 'favicon.ico')];
  var files = [];
  files = glob.readdirSync('**');

  var allFiles = [];

  var patternString = [
    'trade',
    'order',
    'market',
    'securities'
  ];

  files.map((file) => {
    try {
      if (!fs.lstatSync(file).isDirectory() && exclude.indexOf(file) === -1) {
        fs.readFileSync(file).toString().split(/\r?\n/).forEach(function(line){
          patternString.map((pattern) => {
            if (line.indexOf(pattern) !== -1) {
              console.log(file + ' contain `' + pattern + '` in in line "' + line +'";');
              result = 1;
            }
          });
        });
      }
    } catch (e) {
      console.log('Error:', e.stack);
    }
  });
  process.exit(result);

})();

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Calling async method synchronously

You can access the Result property of the task, which will cause your thread to block until the result is available:

string code = GenerateCodeAsync().Result;

Note: In some cases, this might lead to a deadlock: Your call to Result blocks the main thread, thereby preventing the remainder of the async code to execute. You have the following options to make sure that this doesn't happen:

This does not mean that you should just mindlessly add .ConfigureAwait(false) after all your async calls! For a detailed analysis on why and when you should use .ConfigureAwait(false), see the following blog post:

Does it matter what extension is used for SQLite database files?

Pretty much down to personal choice. It may make sense to use an extension based on the database scheme you are storing; treat your database schema as a file format, with SQLite simply being an encoding used for that file format. So, you might use .bookmarks if it's storing bookmarks, or .index if it's being used as an index.

If you want to use a generic extension, I'd use .sqlite3 since that is most descriptive of what version of SQLite is needed to work with the database.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

Match everything except for specified strings

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (red) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\((\b(?!red\b)[\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (frede) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\(([\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = p1.replace(/red/g, '');_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

How to find top three highest salary in emp table in oracle?

 SELECT * FROM 
     (
      SELECT EMPLOYEE, LAST_NAME, SALARY,
      DENSE_RANK() OVER (ORDER BY SALARY DESC) EMPRANK
      FROM emp
     )
    WHERE emprank <= 3;

Running a script inside a docker container using shell script

You could also mount a local directory into your docker image and source the script in your .bashrc. Don't forget the script has to consist of functions unless you want it to execute on every new shell. (This is outdated see the update notice.)

I'm using this solution to be able to update the script outside of the docker instance. This way I don't have to rerun the image if changes occur, I just open a new shell. (Got rid of reopening a shell - see the update notice)

Here is how you bind your current directory:

docker run -it -v $PWD:/scripts $my_docker_build /bin/bash

Now your current directory is bound to /scripts of your docker instance.

(Outdated) To save your .bashrc changes commit your working image with this command:

docker commit $container_id $my_docker_build

Update

To solve the issue to open up a new shell for every change I now do the following:

In the dockerfile itself I add RUN echo "/scripts/bashrc" > /root/.bashrc". Inside zshrc I export the scripts directory to the path. The scripts directory now contains multiple files instead of one. Now I can directly call all scripts without having open a sub shell on every change.

BTW you can define the history file outside of your container too. This way it's not necessary to commit on a bash change anymore.

How to import data from text file to mysql database

LOAD DATA INFILE '/home/userlap/data2/worldcitiespop.txt' INTO TABLE cc FIELDS TERMINATED BY ','LINES TERMINATED BY '\r \n' IGNORE 1 LINES;
  • IGNORE 1 LINES to skip over an initial header line containing column names
  • FIELDS TERMINATED BY ',' is to read the comma-delimited file
  • If you have generated the text file on a Windows system, you might have to use LINES TERMINATED BY '\r\n' to read the file properly, because Windows programs typically use two characters as a line terminator. Some programs, such as WordPad, might use \r as a line terminator when writing files. To read such files, use LINES TERMINATED BY '\r'.

Angular - ui-router get previous state

For sake of readability, I'll place my solution (based of stu.salsbury's anwser) here.

Add this code to your app's abstract template so it runs on every page.

$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from, fromParams) {
    $rootScope.previousState = from.name;
    $rootScope.currentState = to.name;
    console.log('Previous state:'+$rootScope.previousState)
    console.log('Current state:'+$rootScope.currentState)
});

Keeps track of the changes in rootScope. Its pretty handy.

How to downgrade Node version

You can use n for node's version management. There is a simple intro for n.

$ npm install -g n
$ n 6.10.3

this is very easy to use.

then you can show your node version:

$ node -v
v6.10.3

For windows nvm is a well-received tool.

How to get URI from an asset File?

There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.

For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.

Is there a constraint that restricts my generic method to numeric types?

There is no 'good' solution for this yet. However you can narrow the type argument significantly to rule out many missfits for your hypotetical 'INumeric' constraint as Haacked has shown above.

static bool IntegerFunction<T>(T value) where T: IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>, struct {...

Shuffle an array with python, randomize array item order with python

When dealing with regular Python lists, random.shuffle() will do the job just as the previous answers show.

But when it come to ndarray(numpy.array), random.shuffle seems to break the original ndarray. Here is an example:

import random
import numpy as np
import numpy.random

a = np.array([1,2,3,4,5,6])
a.shape = (3,2)
print a
random.shuffle(a) # a will definitely be destroyed
print a

Just use: np.random.shuffle(a)

Like random.shuffle, np.random.shuffle shuffles the array in-place.

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

Position one element relative to another in CSS

I would suggest using absolute positioning within the element.

I've created this to help you visualize it a bit.

_x000D_
_x000D_
#parent {_x000D_
    width:400px;_x000D_
    height:400px;_x000D_
    background-color:white;_x000D_
    border:2px solid blue;_x000D_
    position:relative;_x000D_
}_x000D_
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}_x000D_
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}_x000D_
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}_x000D_
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
_x000D_
<div id="parent">_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>_x000D_
<div id="div3"></div>_x000D_
<div id="div4"></div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/wUrdM/

How to pass a URI to an intent?

The Uri class implements Parcelable, so you can add and extract it directly from the Intent

// Add a Uri instance to an Intent
intent.putExtra("imageUri", uri);

// Get a Uri from an Intent
Uri uri = intent.getParcelableExtra("imageUri");

You can use the same method for any objects that implement Parcelable, and you can implement Parcelable on your own objects if required.

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

how to open popup window using jsp or jquery?

Can be done with in jquery-

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
    $( "#dialog" ).dialog();
    });
    </script>

    <div id="dialog" title="Basic dialog">
    //your form layout
    </div>

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Just another possibility. I had to restart the sql server service to fix this issue for me.

library not found for -lPods

Be sure that you open .xcworkspace, not .xcodeproj

How to loop through Excel files and load them into a database using SSIS package?

I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.

If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.

The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Hope it helps.

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

  • first you cannot extend AsyncTask without override doInBackground
  • second try to create AlterDailog from the builder then call show().

    private boolean visible = false;
    class chkSubscription extends AsyncTask<String, Void, String>
    {
    
        protected void onPostExecute(String result)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setCancelable(true);
            builder.setMessage(sucObject);
            builder.setInverseBackgroundForced(true);
            builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton)
                {
                    dialog.dismiss();
                }
            });
    
            AlertDialog myAlertDialog = builder.create();
            if(visible) myAlertDialog.show();
        }
    
        @Override
        protected String doInBackground(String... arg0)
        {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    
    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        visible = true;
    }
    
    @Override
    protected void onStop()
    {
        visible = false; 
        super.onStop();
    }
    

Twitter Bootstrap modal on mobile devices

We use this code to center the Bootstrap modal dialogs when they open. I haven't had any issue with them on iOS while using this but I'm not sure if it will work for Android.

$('.modal').on('show', function(e) {
    var modal = $(this);
    modal.css('margin-top', (modal.outerHeight() / 2) * -1)
         .css('margin-left', (modal.outerWidth() / 2) * -1);
    return this;
});

npm ERR cb() never called

I had the same problem while installing ionic@beta. I tried the following items and they didn't help me.

  1. npm cache clean
  2. Manually delete cache from %temp%\npm-*
  3. Command prompt "Run As Administrator"

I solved the problem by installing node-v5.10.1-x64.msi (Previous version was node-v5.9.0-x64.msi) and run an npm cache clean before installing ionic@beta

It worked!

vector vs. list in STL

In the case of a vector and list, the main differences that stick out to me are the following:

vector

  • A vector stores its elements in contiguous memory. Therefore, random access is possible inside a vector which means that accessing an element of a vector is very fast because we can simply multiply the base address with the item index to access that element. In fact, it takes only O(1) or constant time for this purpose.

  • Since a vector basically wraps an array, every time you insert an element into the vector (dynamic array), it has to resize itself by finding a new contiguous block of memory to accommodate the new elements which is time-costly.

  • It does not consume extra memory to store any pointers to other elements within it.

list

  • A list stores its elements in non-contiguous memory. Therefore, random access is not possible inside a list which means that to access its elements we have to use the pointers and traverse the list which is slower relative to vector. This takes O(n) or linear time which is slower than O(1).

  • Since a list uses non-contiguous memory, the time taken to insert an element inside a list is a lot more efficient than in the case of its vector counterpart because reallocation of memory is avoided.

  • It consumes extra memory to store pointers to the element before and after a particular element.

So, keeping these differences in mind, we usually consider memory, frequent random access and insertion to decide the winner of vector vs list in a given scenario.

Setting POST variable without using form

Yes, simply set it to another value:

$_POST['text'] = 'another value';

This will override the previous value corresponding to text key of the array. The $_POST is superglobal associative array and you can change the values like a normal PHP array.

Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST array is cleared. A new form submission will generate a new $_POST array.

If you want to persist the value across form submissions, you will need to put it in the form as an input tag's value attribute or retrieve it from a data store.

PUT vs. POST in REST

Here's a simple rule:

PUT to a URL should be used to update or create the resource that can be located at that URL.

POST to a URL should be used to update or create a resource which is located at some other ("subordinate") URL, or is not locatable via HTTP.

Hive ParseException - cannot recognize input near 'end' 'string'

You can always escape the reserved keyword if you still want to make your query work!!

Just replace end with `end`

Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL

CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
    "dynamodb.column.mapping" = "cid:cid,end:end,category:category");

How to query DATETIME field using only date in Microsoft SQL Server?

select *
  from invoice
 where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));

How to set index.html as root file in Nginx?

in your location block you can do:

location / {
  try_files $uri $uri/index.html;
}

which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html

Can't run Curl command inside my Docker Container

This is happening because there is no package cache in the image, you need to run:

apt-get -qq update

before installing packages, and if your command is in a Dockerfile, you'll then need:

apt-get -qq -y install curl

After that install ZSH and GIT Core:

apt-get install zsh
apt-get install git-core

Getting zsh to work in ubuntu is weird since sh does not understand the source command. So, you do this to install zsh:

wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh

and then you change your shell to zsh:

chsh -s `which zsh`

and then restart:

sudo shutdown -r 0

This problem is explained in depth in this issue.

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

jQuery equivalent to Prototype array.last()

According to jsPerf: Last item method, the most performant method is array[array.length-1]. The graph is displaying operations per second, not time per operation.

It is common (but wrong) for developers to think the performance of a single operation matters. It does not. Performance only matters when you're doing LOTS of the same operation. In that case, using a static value (length) to access a specific index (length-1) is fastest, and it's not even close.

How do I test if a recordSet is empty? isNull?

RecordCount is what you want to use.

If Not temp_rst1.RecordCount > 0 ...

C# find highest array value and index

int[] anArray = { 1, 5, 2, 7 };
// Finding max
int m = anArray.Max();

// Positioning max
int p = Array.IndexOf(anArray, m);

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

Accessing inventory host variable in Ansible playbook

[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:

{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:

{{ hostvars[groups['host_group'][0]].node_name }}

How to switch between frames in Selenium WebDriver using Java

First you have to locate the frame id and define it in a WebElement

For ex:- WebElement fr = driver.findElementById("id");

Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");

An example script:-

WebElement fr = driver.findElementById("theIframe");

driver.switchTo().frame(fr);

Then to move out of frame use:- driver.switchTo().defaultContent();

How to increase font size in the Xcode editor?

Easisest solution:

  1. Close any open projects.

  2. Xcode > Preferences > Font & Colors

  3. Make sure to press CMD+A to select all possible text types. Then change the font size from the picker.

enter image description here

How to determine if a list of polygon points are in clockwise order?

As also explained in this Wikipedia article Curve orientation, given 3 points p, q and r on the plane (i.e. with x and y coordinates), you can calculate the sign of the following determinant

enter image description here

If the determinant is negative (i.e. Orient(p, q, r) < 0), then the polygon is oriented clockwise (CW). If the determinant is positive (i.e. Orient(p, q, r) > 0), the polygon is oriented counterclockwise (CCW). The determinant is zero (i.e. Orient(p, q, r) == 0) if points p, q and r are collinear.

In the formula above, we prepend the ones in front of the coordinates of p, q and r because we are using homogeneous coordinates.

Adding maven nexus repo to my pom.xml

From Maven - Settings Reference

The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                  http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <servers>
    <server>
      <id>server001</id>
      <username>my_login</username>
      <password>my_password</password>
      <privateKey>${user.home}/.ssh/id_dsa</privateKey>
      <passphrase>some_passphrase</passphrase>
      <filePermissions>664</filePermissions>
      <directoryPermissions>775</directoryPermissions>
      <configuration></configuration>
    </server>
  </servers>
  ...
</settings>

id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.

username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.

privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.

filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.

Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.

All you should need is the id, username and password

The id and URL should be defined in your pom.xml like this:

<repositories>
    ...
    <repository>
        <id>acme-nexus-releases</id>
        <name>acme nexus</name>
        <url>https://nexus.acme.net/content/repositories/releases</url>
    </repository>
    ...
</repositories>

If you need a username and password to your server, you should encrypt it. Maven Password Encryption

JavaScript: location.href to open in new window/tab?

For example:

    $(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

Working example.

Using grep to search for hex strings in a file

If you want search for printable strings, you can use:

strings -ao filename | grep string

strings will output all printable strings from a binary with offsets, and grep will search within.

If you want search for any binary string, here is your friend:

Dynamic variable names in Bash

This will work too

my_country_code="green"
x="country"

eval z='$'my_"$x"_code
echo $z                 ## o/p: green

In your case

eval final_val='$'magic_way_to_define_magic_variable_"$1"
echo $final_val

iOS 7 status bar back to iOS 6 default style in iPhone app?

This is cross-posted from a blog post I wrote, but here is the full rundown on status bars, navigation bars, and container view controllers on iOS 7:

  1. There is no way to preserve the iOS 6 style status bar layout. The status bar will always overlap your application on iOS 7

  2. Do not confuse status bar appearance with status bar layout. The appearance (light or default) does not affect how the status bar is laid out (frame/height/overlap). It is important to note as well that the system status bar no longer has any background color. When the API refers to UIStatusBarStyleLightContent, they mean white text on a clear background. UIStatusBarStyleDefault is black text on a clear background.

  3. Status bar appearance is controlled along one of two mutually-exclusive basis paths: you can either set them programmatically in the traditional manner, or UIKit will update the appearance for you based on some new properties of UIViewController. The latter option is on by default. Check your app’s plist value for “ViewController-Based Status Bar Appearance” to see which one you’re using. If you set this value to YES, every top-level view controller in your app (other than a standard UIKit container view controller) needs to override preferredStatusBarStyle, returning either the default or the light style. If you edit the plist value to NO, then you can manage the status bar appearance using the familiar UIApplication methods.

  4. UINavigationController will alter the height of its UINavigationBar to either 44 points or 64 points, depending on a rather strange and undocumented set of constraints. If the UINavigationController detects that the top of its view’s frame is visually contiguous with its UIWindow’s top, then it draws its navigation bar with a height of 64 points. If its view’s top is not contiguous with the UIWindow’s top (even if off by only one point), then it draws its navigation bar in the “traditional” way with a height of 44 points. This logic is performed by UINavigationController even if it is several children down inside the view controller hierarchy of your application. There is no way to prevent this behavior.

  5. If you supply a custom navigation bar background image that is only 44 points (88 pixels) tall, and the UINavigationController’s view’s bounds matches the UIWindow’s bounds (as discussed in #4), the UINavigationController will draw your image in the frame (0,20,320,44), leaving 20 points of opaque black space above your custom image. This may confuse you into thinking you are a clever developer who bypassed rule #1, but you are mistaken. The navigation bar is still 64 points tall. Embedding a UINavigationController in a slide-to-reveal style view hierarchy makes this abundantly clear.

  6. Beware of the confusingly-named edgesForExtendedLayout property of UIViewController. Adjusting edgesForExtendedLayout does nothing in most cases. The only way UIKit uses this property is if you add a view controller to a UINavigationController, then the UINavigationController uses edgesForExtendedLayout to determine whether or not its child view controller should be visible underneath the navigation bar / status bar area. Setting edgesForExtendedLayout on the UINavigationController itself does nothing to alter whether or not the UINavigationController has a 44 or 64 point high navigation bar area. See #4 for that logic. Similar layout logic applies to the bottom of your view when using a toolbar or UITabBarController.

  7. If all you are trying to do is prevent your custom child view controller from underlapping the navigation bar when inside a UINavigationController, then set edgesForExtendedLayout to UIRectEdgeNone (or at least a mask that excludes UIRectEdgeTop). Set this value as early as possible in the life cycle of your view controller.

  8. UINavigationController and UITabBarController will also try to pad the contentInsets of table views and collection views in its subview hierarchy. It does this in a manner similar to the status bar logic from #4. There is a programmatic way of preventing this, by setting automaticallyAdjustsScrollViewInsets to NO for your table views and collection views (it defaults to YES). This posed some serious problems for Whisper and Riposte, since we use contentInset adjustments to control the layout of table views in response to toolbar and keyboard movements.

  9. To reiterate: there is no way to return to iOS 6 style status bar layout logic. In order to approximate this, you have to move all the view controllers of your app into a container view that is offset by 20 points from the top of the screen, leaving an intentionally black view behind the status bar to simulate the old appearance. This is the method we ended up using in Riposte and Whisper.

  10. Apple is pushing very hard to ensure that you don’t try to do #9. They want us to redesign all our apps to underlap the status bar. There are many cogent arguments, however, for both user experience and technical reasons, why this is not always a good idea. You should do what is best for your users and not simply follow the whimsy of the platform.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Seems to be a typo error in that package of gcc. The solution:

mv /usr/include/c++/4.x/i486-linux-gnu /usr/include/c++/4.x/i686-linux-gnu/64

IntelliJ how to zoom in / out

You need to look for the Increase Font Size and Decrease Font Size options on the Keymap menu, you can see the options on my screenshot. You will find the Keymap menu under Preferences > Keymap.

font size settings

Assigning on those will have the expected effect for font zoom.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

TypeError: list indices must be integers or slices, not str

I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.

Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.

Test for existence of nested JavaScript object key

The answer given by CMS works fine with the following modification for null checks as well

function checkNested(obj /*, level1, level2, ... levelN*/) 
      {
             var args = Array.prototype.slice.call(arguments),
             obj = args.shift();

            for (var i = 0; i < args.length; i++) 
            {
                if (obj == null || !obj.hasOwnProperty(args[i]) ) 
                {
                    return false;
                }
                obj = obj[args[i]];
            }
            return true;
    }

How to check if an int is a null

In Java there isn't Null values for primitive Data types. If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer. When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.

In this case you must use Inter instead of int

Try below snippet and see example for more info,

Integer id;
String name;

//Refer this example
    Integer val = 0;

`

if (val != null){
System.out.println("value is not null");
}

`

Also you can assign Null as below,

val = null;

Read tab-separated file line into array

You could also try,

OIFS=$IFS;
IFS="\t";

animals=`cat animals.txt`
animalArray=$animals;

for animal in $animalArray
do
    echo $animal
done

IFS=$OIFS;

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I was facing the same issue. So, i created a stored Procedure and defined the size like @FromDate datetime, @ToDate datetime, @BL varchar(50)

After defining the size in @BL varchar(50), i did not face any problem. Now it is working fine

React onClick and preventDefault() link refresh/redirect?

I've had some troubles with anchor tags and preventDefault in the past and I always forget what I'm doing wrong, so here's what I figured out.

The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault():

function (e, { href }) {
  e.preventDefault();
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

It seems the destructuring causes an error (Cannot read property 'href' of undefined) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

function (e) {
  e.preventDefault();
  const { href } = e.target;
  // Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>

I hope this helps other people like me puzzled by not shown errors!

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

Very similar to Marc, only difference I would make would be to spool to a parameter like so:

WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON

spool &1

-- Code

spool off
exit

And then to call the SQLPLUS as

sqlplus -s username/password@sid @tmp.sql /tmp/output.txt

Has anyone gotten HTML emails working with Twitter Bootstrap?

Hi Brian Armstrong, visit this link.

This blog tells you how to integrate Rails with Bootstrap less (using premailer-rails).

If you're using bootstrap sass, you could do the same:

start by importing some Bootstrap sass files into email.css.scss

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";
@import 'bootstrap/normalize';
@import 'bootstrap/tables';
@import 'bootstrap/progress-bars';

and then in your view <head> section add <%= stylesheet_link_tag "email" %>

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Making HTTP Requests using Chrome Developer tools

To GET requests with headers, use this format.

   fetch('http://example.com', {
      method: 'GET',
      headers: new Headers({
               'Content-Type': 'application/json',
               'someheader': 'headervalue'
               })
    })
    .then(res => res.json())
    .then(console.log)

How can I undo a `git commit` locally and on a remote after `git push`

Try using

git reset --hard <commit id> 

Please Note : Here commit id will the id of the commit you want to go to but not the id you want to reset. this was the only point where i also got stucked.

then push

git push -f <remote> <branch>

"No X11 DISPLAY variable" - what does it mean?

One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.

How to highlight a current menu item?

For AngularUI Router users:

<a ui-sref-active="active" ui-sref="app">

And that will place an active class on the object that is selected.

Passing arguments to angularjs filters

You can simply do like this In Template

<span ng-cloak>{{amount |firstFiler:'firstArgument':'secondArgument' }}</span>

In filter

angular.module("app")
.filter("firstFiler",function(){

    console.log("filter loads");
    return function(items, firstArgument,secondArgument){
        console.log("item is ",items); // it is value upon which you have to filter
        console.log("firstArgument is ",firstArgument);
        console.log("secondArgument ",secondArgument);

        return "hello";
    }
    });

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

C++ multiline string literal

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

The indentation doesn't matter, since it's not inside the quotes.

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

How can I solve the error LNK2019: unresolved external symbol - function?

Since I want my project to compile to a stand-alone EXE file, I linked the UnitTest project to the function.obj file generated from function.cpp and it works.

Right click on the 'UnitTest1' project ? Configuration Properties ? Linker ? Input ? Additional Dependencies ? add "..\MyProjectTest\Debug\function.obj".

Check if the number is integer

It appears that you do not see the need to incorporate some error tolerance. It would not be needed if all integers came entered as integers, however sometimes they come as a result of arithmetic operations that loose some precision. For example:

> 2/49*49
[1] 2
> check.integer(2/49*49)
[1] FALSE 
> is.wholenumber(2/49*49)
[1] TRUE

Note that this is not R's weakness, all computer software have some limits of precision.

check if variable empty

You can check if it's not set (or empty) in a number of ways.

if (!$var){ }

Or:

if ($var === null){ } // This checks if the variable, by type, IS null.

Or:

if (empty($var)){ }

You can check if it's declared with:

if (!isset($var)){ }

Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.

How to uncheck checkbox using jQuery Uniform library

checkbox that act like radio btn

$(".checkgroup").live('change',function() { var previous=this.checked; $(".checkgroup).attr("checked", false); $(this).attr("checked", previous); });

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

Replacing blank values (white space) with NaN in pandas

print(df.isnull().sum()) # check numbers of null value in each column

modifiedDf=df.fillna("NaN") # Replace empty/null values with "NaN"

# modifiedDf = fd.dropna() # Remove rows with empty values

print(modifiedDf.isnull().sum()) # check numbers of null value in each column

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

Pass variables to Ruby script via command line

Unfortunately, Ruby does not support such passing mechanism as e.g. AWK:

> awk -v a=1 'BEGIN {print a}'
> 1

It means you cannot pass named values into your script directly.

Using cmd options may help:

> ruby script.rb val_0 val_1 val_2

# script.rb
puts ARGV[0] # => val_0
puts ARGV[1] # => val_1
puts ARGV[2] # => val_2

Ruby stores all cmd arguments in the ARGV array, the scriptname itself can be captured using the $PROGRAM_NAME variable.

The obvious disadvantage is that you depend on the order of values.

If you need only Boolean switches use the option -s of the Ruby interpreter:

> ruby -s -e 'puts "So do I!" if $agreed' -- -agreed
> So do I!

Please note the -- switch, otherwise Ruby will complain about a nonexistent option -agreed, so pass it as a switch to your cmd invokation. You don't need it in the following case:

> ruby -s script_with_switches.rb -agreed
> So do I!

The disadvantage is that you mess with global variables and have only logical true/false values.

You can access values from environment variables:

> FIRST_NAME='Andy Warhol' ruby -e 'puts ENV["FIRST_NAME"]'
> Andy Warhol

Drawbacks are present here to, you have to set all the variables before the script invocation (only for your ruby process) or to export them (shells like BASH):

> export FIRST_NAME='Andy Warhol'
> ruby -e 'puts ENV["FIRST_NAME"]'

In the latter case, your data will be readable for everybody in the same shell session and for all subprocesses, which can be a serious security implication.

And at least you can implement an option parser using getoptlong and optparse.

Happy hacking!

change type of input field with jQuery

I received the same error message while attempting to do this in Firefox 5.

I solved it using the code below:

<script type="text/javascript" language="JavaScript">

$(document).ready(function()
{
    var passfield = document.getElementById('password_field_id');
    passfield.type = 'text';
});

function focusCheckDefaultValue(field, type, defaultValue)
{
    if (field.value == defaultValue)
    {
        field.value = '';
    }
    if (type == 'pass')
    {
        field.type = 'password';
    }
}
function blurCheckDefaultValue(field, type, defaultValue)
{
    if (field.value == '')
    {
        field.value = defaultValue;
    }
    if (type == 'pass' && field.value == defaultValue)
    {
        field.type = 'text';
    }
    else if (type == 'pass' && field.value != defaultValue)
    {
        field.type = 'password';
    }
}

</script>

And to use it, just set the onFocus and onBlur attributes of your fields to something like the following:

<input type="text" value="Username" name="username" id="username" 
    onFocus="javascript:focusCheckDefaultValue(this, '', 'Username -OR- Email Address');"
    onBlur="javascript:blurCheckDefaultValue(this, '', 'Username -OR- Email Address');">

<input type="password" value="Password" name="pass" id="pass"
    onFocus="javascript:focusCheckDefaultValue(this, 'pass', 'Password');"
    onBlur="javascript:blurCheckDefaultValue(this, 'pass', 'Password');">

I use this for a username field as well, so it toggles a default value. Just set the second parameter of the function to '' when you call it.

Also it might be worth noting that the default type of my password field is actually password, just in case a user doesn't have javascript enabled or if something goes wrong, that way their password is still protected.

The $(document).ready function is jQuery, and loads when the document has finished loading. This then changes the password field to a text field. Obviously you'll have to change 'password_field_id' to your password field's id.

Feel free to use and modify the code!

Hope this helps everyone who had the same problem I did :)

-- CJ Kent

EDIT: Good solution but not absolute. Works on on FF8 and IE8 BUT not fully on Chrome(16.0.912.75 ver). Chrome does not display the Password text when the page loads. Also - FF will display your password when autofill is switched on.

Draw Circle using css alone

Yep, draw a box and give it a border radius that is half the width of the box:

#circle {
    background: #f00;
    width: 200px;
    height: 200px;
    border-radius: 50%;
}

Working demo:

http://jsfiddle.net/DsW9h/1/

_x000D_
_x000D_
#circle {_x000D_
    background: #f00;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div id="circle"></div>
_x000D_
_x000D_
_x000D_

C++ program converts fahrenheit to celsius

Best way would be

#include <iostream>                        
using namespace std;                       

int main() {                               
    float celsius;                         
    float fahrenheit;

    cout << "Enter Celsius temperature: "; 
    cin >> celsius;
    fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
    cout << "Fahrenheit = " << fahrenheit << endl;

    return 0;                             
}

:)

SQL Server ORDER BY date and nulls last

According to Itzik Ben-Gan, author of T-SQL Fundamentals for MS SQL Server 2012, "By default, SQL Server sorts NULL marks before non-NULL values. To get NULL marks to sort last, you can use a CASE expression that returns 1 when the" Next_Contact_Date column is NULL, "and 0 when it is not NULL. Non-NULL marks get 0 back from the expression; therefore, they sort before NULL marks (which get 1). This CASE expression is used as the first sort column." The Next_Contact_Date column "should be specified as the second sort column. This way, non-NULL marks sort correctly among themselves." Here is the solution query for your example for MS SQL Server 2012 (and SQL Server 2014):

ORDER BY 
   CASE 
        WHEN Next_Contact_Date IS NULL THEN 1
        ELSE 0
   END, Next_Contact_Date;

Equivalent code using IIF syntax:

ORDER BY 
   IIF(Next_Contact_Date IS NULL, 1, 0),
   Next_Contact_Date;

How to generate XML file dynamically using PHP?

I'd use SimpleXMLElement.

<?php

$xml = new SimpleXMLElement('<xml/>');

for ($i = 1; $i <= 8; ++$i) {
    $track = $xml->addChild('track');
    $track->addChild('path', "song$i.mp3");
    $track->addChild('title', "Track $i - Track Title");
}

Header('Content-type: text/xml');
print($xml->asXML());

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

Linux - Install redis-cli only

I made a simple pure-go solution, which is under development.

redis-cli: https://github.com/holys/redis-cli

Build once, and run everywhere. Fully portable.

Please feel free to have a try.

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Simplified version for Oracle. If you don't want to create OracleParameter

var sql = "Update [User] SET FirstName = :p0 WHERE Id = :p1";
context.Database.ExecuteSqlCommand(sql, firstName, id);

How to handle notification when app in background in Firebase

Remove notification payload completely from your server request. Send only data and handle it in onMessageReceived(), otherwise your onMessageReceived will not be triggered when the app is in background or killed.

Here is what I am sending from server:

{
  "data":{
    "id": 1,
    "missedRequests": 5
    "addAnyDataHere": 123
  },
  "to": "fhiT7evmZk8:APA91bFJq7Tkly4BtLRXdYvqHno2vHCRkzpJT8QZy0TlIGs......"
}

So you can receive your data in onMessageReceived(RemoteMessage message) like this: (let's say I have to get the id)

Object obj = message.getData().get("id");
        if (obj != null) {
            int id = Integer.valueOf(obj.toString());
        }

And similarly you can get any data which you have sent from server within onMessageReceived().

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

How to change DataTable columns order

Try to use the DataColumn.SetOrdinal method. For example:

dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1); 

UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:

Extension method:

public static class DataTableExtensions
{
    public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
    {
        int columnIndex = 0;
        foreach(var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

Usage:

table.SetColumnsOrder("Qty", "Unit", "Id");

or

table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});

No output to console from a WPF application?

Although John Leidegren keeps shooting down the idea, Brian is correct. I've just got it working in Visual Studio.

To be clear a WPF application does not create a Console window by default.

You have to create a WPF Application and then change the OutputType to "Console Application". When you run the project you will see a console window with your WPF window in front of it.

It doesn't look very pretty, but I found it helpful as I wanted my app to be run from the command line with feedback in there, and then for certain command options I would display the WPF window.

Creating virtual directories in IIS express

A new option is Jexus Manager for IIS Express,

https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/

It is just the management tool you know how to use.

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

Get PHP class property by string

Something like this? Haven't tested it but should work fine.

function magic($obj, $var, $value = NULL)
{
    if($value == NULL)
    {
        return $obj->$var;
    }
    else
    {
        $obj->$var = $value;
    }
}

Alternative to file_get_contents?

If you have it available, using curl is your best option.

You can see if it is enabled by doing phpinfo() and searching the page for curl.

If it is enabled, try this:

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, SITE_PATH . 'cms/data.php');
$xml_file = curl_exec($curl_handle);
curl_close($curl_handle);

What is the difference between canonical name, simple name and class name in Java Class?

Adding local classes, lambdas and the toString() method to complete the previous two answers. Further, I add arrays of lambdas and arrays of anonymous classes (which do not make any sense in practice though):

package com.example;

public final class TestClassNames {
    private static void showClass(Class<?> c) {
        System.out.println("getName():          " + c.getName());
        System.out.println("getCanonicalName(): " + c.getCanonicalName());
        System.out.println("getSimpleName():    " + c.getSimpleName());
        System.out.println("toString():         " + c.toString());
        System.out.println();
    }

    private static void x(Runnable r) {
        showClass(r.getClass());
        showClass(java.lang.reflect.Array.newInstance(r.getClass(), 1).getClass()); // Obtains an array class of a lambda base type.
    }

    public static class NestedClass {}

    public class InnerClass {}

    public static void main(String[] args) {
        class LocalClass {}
        showClass(void.class);
        showClass(int.class);
        showClass(String.class);
        showClass(Runnable.class);
        showClass(SomeEnum.class);
        showClass(SomeAnnotation.class);
        showClass(int[].class);
        showClass(String[].class);
        showClass(NestedClass.class);
        showClass(InnerClass.class);
        showClass(LocalClass.class);
        showClass(LocalClass[].class);
        Object anonymous = new java.io.Serializable() {};
        showClass(anonymous.getClass());
        showClass(java.lang.reflect.Array.newInstance(anonymous.getClass(), 1).getClass()); // Obtains an array class of an anonymous base type.
        x(() -> {});
    }
}

enum SomeEnum {
   BLUE, YELLOW, RED;
}

@interface SomeAnnotation {}

This is the full output:

getName():          void
getCanonicalName(): void
getSimpleName():    void
toString():         void

getName():          int
getCanonicalName(): int
getSimpleName():    int
toString():         int

getName():          java.lang.String
getCanonicalName(): java.lang.String
getSimpleName():    String
toString():         class java.lang.String

getName():          java.lang.Runnable
getCanonicalName(): java.lang.Runnable
getSimpleName():    Runnable
toString():         interface java.lang.Runnable

getName():          com.example.SomeEnum
getCanonicalName(): com.example.SomeEnum
getSimpleName():    SomeEnum
toString():         class com.example.SomeEnum

getName():          com.example.SomeAnnotation
getCanonicalName(): com.example.SomeAnnotation
getSimpleName():    SomeAnnotation
toString():         interface com.example.SomeAnnotation

getName():          [I
getCanonicalName(): int[]
getSimpleName():    int[]
toString():         class [I

getName():          [Ljava.lang.String;
getCanonicalName(): java.lang.String[]
getSimpleName():    String[]
toString():         class [Ljava.lang.String;

getName():          com.example.TestClassNames$NestedClass
getCanonicalName(): com.example.TestClassNames.NestedClass
getSimpleName():    NestedClass
toString():         class com.example.TestClassNames$NestedClass

getName():          com.example.TestClassNames$InnerClass
getCanonicalName(): com.example.TestClassNames.InnerClass
getSimpleName():    InnerClass
toString():         class com.example.TestClassNames$InnerClass

getName():          com.example.TestClassNames$1LocalClass
getCanonicalName(): null
getSimpleName():    LocalClass
toString():         class com.example.TestClassNames$1LocalClass

getName():          [Lcom.example.TestClassNames$1LocalClass;
getCanonicalName(): null
getSimpleName():    LocalClass[]
toString():         class [Lcom.example.TestClassNames$1LocalClass;

getName():          com.example.TestClassNames$1
getCanonicalName(): null
getSimpleName():    
toString():         class com.example.TestClassNames$1

getName():          [Lcom.example.TestClassNames$1;
getCanonicalName(): null
getSimpleName():    []
toString():         class [Lcom.example.TestClassNames$1;

getName():          com.example.TestClassNames$$Lambda$1/1175962212
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212
getSimpleName():    TestClassNames$$Lambda$1/1175962212
toString():         class com.example.TestClassNames$$Lambda$1/1175962212

getName():          [Lcom.example.TestClassNames$$Lambda$1;
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212[]
getSimpleName():    TestClassNames$$Lambda$1/1175962212[]
toString():         class [Lcom.example.TestClassNames$$Lambda$1;

So, here are the rules. First, lets start with primitive types and void:

  1. If the class object represents a primitive type or void, all the four methods simply returns its name.

Now the rules for the getName() method:

  1. Every non-lambda and non-array class or interface (i.e, top-level, nested, inner, local and anonymous) has a name (which is returned by getName()) that is the package name followed by a dot (if there is a package), followed by the name of its class-file as generated by the compiler (whithout the suffix .class). If there is no package, it is simply the name of the class-file. If the class is an inner, nested, local or anonymous class, the compiler should generate at least one $ in its class-file name. Note that for anonymous classes, the class name would end with a dollar-sign followed by a number.
  2. Lambda class names are generally unpredictable, and you shouldn't care about they anyway. Exactly, their name is the name of the enclosing class, followed by $$Lambda$, followed by a number, followed by a slash, followed by another number.
  3. The class descriptor of the primitives are Z for boolean, B for byte, S for short, C for char, I for int, J for long, F for float and D for double. For non-array classes and interfaces the class descriptor is L followed by what is given by getName() followed by ;. For array classes, the class descriptor is [ followed by the class descriptor of the component type (which may be itself another array class).
  4. For array classes, the getName() method returns its class descriptor. This rule seems to fail only for array classes whose the component type is a lambda (which possibly is a bug), but hopefully this should not matter anyway because there is no point even on the existence of array classes whose component type is a lambda.

Now, the toString() method:

  1. If the class instance represents an interface (or an annotation, which is a special type of interface), the toString() returns "interface " + getName(). If it is a primitive, it returns simply getName(). If it is something else (a class type, even if it is a pretty weird one), it returns "class " + getName().

The getCanonicalName() method:

  1. For top-level classes and interfaces, the getCanonicalName() method returns just what the getName() method returns.
  2. The getCanonicalName() method returns null for anonymous or local classes and for array classes of those.
  3. For inner and nested classes and interfaces, the getCanonicalName() method returns what the getName() method would replacing the compiler-introduced dollar-signs by dots.
  4. For array classes, the getCanonicalName() method returns null if the canonical name of the component type is null. Otherwise, it returns the canonical name of the component type followed by [].

The getSimpleName() method:

  1. For top-level, nested, inner and local classes, the getSimpleName() returns the name of the class as written in the source file.
  2. For anonymous classes the getSimpleName() returns an empty String.
  3. For lambda classes the getSimpleName() just returns what the getName() would return without the package name. This do not makes much sense and looks like a bug for me, but there is no point in calling getSimpleName() on a lambda class to start with.
  4. For array classes the getSimpleName() method returns the simple name of the component class followed by []. This have the funny/weird side-effect that array classes whose component type is an anonymous class have just [] as their simple names.

How to ping multiple servers and return IP address and Hostnames using batch script?

the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.

better do it this way

ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping

overall this looks like this:

@echo off
SetLocal


set log=path/to/logfile.txt
set check=path/to/checkfile.txt

:start
echo. some echo date >>%log%

:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof

:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

:error
echo. some errormessage to >>%log%
echo. some blat to mail?

:eof
echo. some good message to >>%log%

MySQL integer field is returned as string in PHP

In my case mysqlnd.so extension had been installed. BUT i hadn't pdo_mysqlnd.so. So, the problem had been solved by replacing pdo_mysql.so with pdo_mysqlnd.so.

Command to get time in milliseconds

Perl can be used for this, even on exotic platforms like AIX. Example:

#!/usr/bin/perl -w

use strict;
use Time::HiRes qw(gettimeofday);

my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
    localtime ($t_sec);

printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
    1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

Creating an abstract class in Objective-C

Changing a little what @redfood suggested by applying @dotToString's comment, you actually have the solution adopted by Instagram's IGListKit.

  1. Create a protocol for all the methods that make no sense to be defined in the base (abstract) class i.e. they need specific implementations in the children.
  2. Create a base (abstract) class that does not implement this protocol. You can add to this class any other methods that make sense to have a common implementation.
  3. Everywhere in your project, if a child from AbstractClass must be input to or output by some method, type it as AbstractClass<Protocol> instead.

Because AbstractClass does not implement Protocol, the only way to have an AbstractClass<Protocol> instance is by subclassing. As AbstractClass alone can't be used anywhere in the project, it becomes abstract.

Of course, this doesn't prevent unadvised developers from adding new methods referring simply to AbstractClass, which would end up allowing an instance of the (not anymore) abstract class.

Real world example: IGListKit has a base class IGListSectionController which doesn't implement the protocol IGListSectionType, however every method that requires an instance of that class, actually asks for the type IGListSectionController<IGListSectionType>. Therefore there's no way to use an object of type IGListSectionController for anything useful in their framework.

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

linq where list contains any in list

If you use HashSet instead of List for listofGenres you can do:

var genres = new HashSet<Genre>() { "action", "comedy" };   
var movies = _db.Movies.Where(p => genres.Overlaps(p.Genres));

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Can not connect to local PostgreSQL

This is how I solved that error message, based partly on wildplasser's answer.

find / -name .s.PGSQL.5432 -ls 2> /dev/null
  => ... /tmp/.s.PGSQL.5432

So, there's my socket or whatever, but the client looks for it at:

/var/run/postgresql/.s.PGSQL.5432

So quite simply make a symbolic link to the /tmp/.s.PGSQL.5432:

sudo ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432

Hope this helps to anyone. The seems kind of wrong, but hey, it works!

Bitwise operation and usage

Another common use-case is manipulating/testing file permissions. See the Python stat module: http://docs.python.org/library/stat.html.

For example, to compare a file's permissions to a desired permission set, you could do something like:

import os
import stat

#Get the actual mode of a file
mode = os.stat('file.txt').st_mode

#File should be a regular file, readable and writable by its owner
#Each permission value has a single 'on' bit.  Use bitwise or to combine 
#them.
desired_mode = stat.S_IFREG|stat.S_IRUSR|stat.S_IWUSR

#check for exact match:
mode == desired_mode
#check for at least one bit matching:
bool(mode & desired_mode)
#check for at least one bit 'on' in one, and not in the other:
bool(mode ^ desired_mode)
#check that all bits from desired_mode are set in mode, but I don't care about 
# other bits.
not bool((mode^desired_mode)&desired_mode)

I cast the results as booleans, because I only care about the truth or falsehood, but it would be a worthwhile exercise to print out the bin() values for each one.

How to retrieve the current version of a MySQL database management system (DBMS)?

Only this code works for me

/usr/local/mysql/bin/mysql -V  

Adding IN clause List to a JPA Query

You must convert to List as shown below:

    String[] valores = hierarquia.split(".");       
    List<String> lista =  Arrays.asList(valores);

    String jpqlQuery = "SELECT a " +
            "FROM AcessoScr a " +
            "WHERE a.scr IN :param ";

    Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);                   
    query.setParameter("param", lista);     
    List<AcessoScr> acessos = query.getResultList();

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

Streaming video from Android camera to server

I'm looking into this as well, and while I don't have a good solution for you I did manage to dig up SIPDroid's video code:

http://code.google.com/p/sipdroid/source/browse/trunk/src/org/sipdroid/sipua/ui/VideoCamera.java

OperationalError: database is locked

UPDATE django version 2.1.7

I got this error sqlite3.OperationalError: database is locked using pytest with django.

Solution:

If we are using @pytest.mark.django_db decorator. What it does is create a in-memory-db for testing.

Named: file:memorydb_default?mode=memory&cache=shared We can get this name with:

from django.db import connection
db_path = connection.settings_dict['NAME']

To access this database and also edit it, do:

Connect to the data base:

with sqlite3.connect(db_path, uri=True) as conn:
    c = conn.cursor()

Use uri=True to specifies the disk file that is the SQLite database to be opened.

To avoid the error activate transactions in the decorator:

@pytest.mark.django_db(transaction=True)

Final function:

from django.db import connection

@pytest.mark.django_db(transaction=True)
def test_mytest():
    db_path = connection.settings_dict['NAME']
    with sqlite3.connect(db_path, uri=True) as conn:
        c = conn.cursor()
        c.execute('my amazing query')
        conn.commit()
    assert ... == ....

Uncaught ReferenceError: $ is not defined

This is what solved it for me. Originally I went to Google and copied and pasted their suggested snippet for jQuery on their CDN page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

The snippet does not include the HTTP: or HTTPS: in the src attribute but my browser, FireFox, needed it so I changed it to: edit: this worked for me with Google Chrome as well

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Then it worked.

How do I use a pipe to redirect the output of one command to the input of another?

You can also run exactly same command at Cmd.exe command-line using PowerShell. I'd go with this approach for simplicity...

C:\>PowerShell -Command "temperature | prismcom.exe usb"

Please read up on Understanding the Windows PowerShell Pipeline

You can also type in C:\>PowerShell at the command-line and it'll put you in PS C:\> mode instanctly, where you can directly start writing PS.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

if You use spring boot , you should add origin link in the @CrossOrigin annotation

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")

You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/

How can I show an image using the ImageView component in javafx and fxml?

Please find below example to load image using JavaFX.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;

    public class LoadImage extends Application {

    public static void main(String[] args) {
    Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
    primaryStage.setTitle("Load Image");

    StackPane sp = new StackPane();
    Image img = new Image("javafx.jpg");
    ImageView imgView = new ImageView(img);
    sp.getChildren().add(imgView);

    //Adding HBox to the scene
    Scene scene = new Scene(sp);
    primaryStage.setScene(scene);
    primaryStage.show();
    }

  }

Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.

Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");

Posting form to different MVC post action depending on the clicked submit button

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

In this way you don't need to do anything special on the server side.

Of course, you can use Url extensions methods in your Razor to specify the form action.

For browsers supporting HMTL5: simply define your submit buttons like this:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsers I recommend using an unobtrusive script like this (include it in your "master layout"):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submit and data-form-action attributes. When this happens, it takes the value of data-form-action attribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

Then you simply have to add a data-form-action attribute with the desired action URL to your button, like this:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

As you can see, this requires no custom routing, you can use the standard Url extension methods, and you have nothing special to do in modern browsers.

Changing SVG image color with javascript

Built off the above but with dynamic creation and a vector image, not drawing.

function svgztruck() {
    tok = "{d path value}"
    return tok;
}

function buildsvg( eid ) {
    console.log("building");
    var zvg = "svg" + eid;
    var vvg = eval( zvg );
    var raw = vvg();

    var svg = document.getElementById( eid );
    svg.setAttributeNS(null,"d", raw );
    svg.setAttributeNS(null,"fill","green");
    svg.setAttributeNS(null,"onlick", eid + ".style.fill=#FF0000");
    return;
}

You could call with:

<img src="" onerror="buildscript">

Now you can add colors by sub element and manipulate all elements of the dom directly. It is important to implement your viewbox and height width first on the svg html, not done in the example above.

There is no need to make your code 10 pages when it could be one... but who am I to argue. Better use PHP while your at it.

The inner element that svg builds on is a simple <svg lamencoding id=parenteid><path id=eid><svg> with nothing else.

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

If you have @oneToOne mapping set to FetchType.LAZY and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.

Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.

Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

if somebody wants to change the battery and text color of the status bar like the below image:

enter image description here

you can use the following code in the appdelegate class.

UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]

How do I create an Android Spinner as a popup?

Adding a small attribute as android:spinnerMode="dialog" would show the spinner contents in a pop-up.

Passing additional variables from command line to make

From the manual:

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

So you can do (from bash):

FOOBAR=1 make

resulting in a variable FOOBAR in your Makefile.

What is the difference between exit(0) and exit(1) in C?

The difference is the value returned to the environment is 0 in the former case and 1 in the latter case:

$ ./prog_with_exit_0
$ echo $?
0
$

and

$ ./prog_with_exit_1
$ echo $?
1
$

Also note that the macros value EXIT_SUCCESS and EXIT_FAILURE used as an argument to exit function are implementation defined but are usually set to respectively 0 and a non-zero number. (POSIX requires EXIT_SUCCESS to be 0). So usually exit(0) means a success and exit(1) a failure.

An exit function call with an argument in main function is equivalent to the statement return with the same argument.

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

Best-for-now Legacy Browser Frame Breaking Script

The other solutions did not worked for me. This one works on all browsers:

One way to defend against clickjacking is to include a "frame-breaker" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.

In the document HEAD element, add the following:

<style id="antiClickjack">body{display:none !important;}</style>

First apply an ID to the style element itself:

<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       top.location = self.location;
   }
</script>

This way, everything can be in the document HEAD and you only need one method/taglib in your API.

Reference: https://www.codemagi.com/blog/post/194

How to create global variables accessible in all views using Express / Node.JS?

You can do this by adding them to the locals object in a general middleware.

app.use(function (req, res, next) {
   res.locals = {
     siteTitle: "My Website's Title",
     pageTitle: "The Home Page",
     author: "Cory Gross",
     description: "My app's description",
   };
   next();
});

Locals is also a function which will extend the locals object rather than overwriting it. So the following works as well

res.locals({
  siteTitle: "My Website's Title",
  pageTitle: "The Home Page",
  author: "Cory Gross",
  description: "My app's description",
});

Full example

var app = express();

var middleware = {

    render: function (view) {
        return function (req, res, next) {
            res.render(view);
        }
    },

    globalLocals: function (req, res, next) {
        res.locals({ 
            siteTitle: "My Website's Title",
            pageTitle: "The Root Splash Page",
            author: "Cory Gross",
            description: "My app's description",
        });
        next();
    },

    index: function (req, res, next) {
        res.locals({
            indexSpecificData: someData
        });
        next();
    }

};


app.use(middleware.globalLocals);
app.get('/', middleware.index, middleware.render('home'));
app.get('/products', middleware.products, middleware.render('products'));

I also added a generic render middleware. This way you don't have to add res.render to each route which means you have better code reuse. Once you go down the reusable middleware route you'll notice you will have lots of building blocks which will speed up development tremendously.

How to mock location on device?

I wrote an App that runs a WebServer (REST-Like) on your Android Phone, so you can set the GPS position remotely. The website provides an Map on which you can click to set a new position, or use the "wasd" keys to move in any direction. The app was a quick solution so there is nearly no UI nor Documentation, but the implementation is straight forward and you can look everything up in the (only four) classes.

Project repository: https://github.com/juliusmh/RemoteGeoFix

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Use DateTime.TryParseExact() if you want to match against a specific date format

   string format = "yyyyMMdd"; 
    DateTime dateTime;
    DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
                                             DateTimeStyles.None, out dateTime);