Programs & Examples On #Nested exceptions

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Why is synchronized block better than synchronized method?

Define 'better'. A synchronized block is only better because it allows you to:

  1. Synchronize on a different object
  2. Limit the scope of synchronization

Now your specific example is an example of the double-checked locking pattern which is suspect (in older Java versions it was broken, and it is easy to do it wrong).

If your initialization is cheap, it might be better to initialize immediately with a final field, and not on the first request, it would also remove the need for synchronization.

Laravel Eloquent "WHERE NOT IN"

You can use WhereNotIn in the following way:

$category=DB::table('category')
          ->whereNotIn('category_id',[14 ,15])
          ->get();`enter code here`

Calculate rolling / moving average in C++

One way can be to circularly store the values in the buffer array. and calculate average this way.

int j = (int) (counter % size);
buffer[j] = mostrecentvalue;
avg = (avg * size - buffer[j - 1 == -1 ? size - 1 : j - 1] + buffer[j]) / size;

counter++;

// buffer[j - 1 == -1 ? size - 1 : j - 1] is the oldest value stored

The whole thing runs in a loop where most recent value is dynamic.

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Find the last time table was updated

Find last time of update on a table

SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()

http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html

How to capture multiple repeated groups?

With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the + quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.

You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).

Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:

^([A-Z]+),([A-Z]+),([A-Z]+)$

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

Submit form without page reloading

You either use AJAX or you

  • create and append an iframe to the document
  • set the iframes name to 'foo'
  • set the forms target to 'foo'
  • submit
  • have the forms action render javascript with 'parent.notify(...)' to give feedback
  • optionally you can remove the iframe

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

After 7 long hours of searching I finally found the way!! None of the above solutions worked, only one of them pointed towards the issue!

If you are on Win7, then your Firewall blocks the SDK Manager from retrieving the addon list. You will have to add "android.bat" and "java.exe" to the trusted files and bingo! everything will start working!!

sql primary key and index

NOTE: This answer addresses enterprise-class development in-the-large.

This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.

In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.

Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.

The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.

I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.

All combinations of a list of lists

you need itertools.product:

>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Why do I get "MismatchSenderId" from GCM server side?

I encountered the same issue recently and I tried different values for "gcm_sender_id" based on the project ID. However, the "gcm_sender_id" value must be set to the "Project Number".

You can find this value under: Menu > IAM & Admin > Settings.

See screenshot: GCM Project Number

Android: How to get a custom View's height and width?

You can use the following method to get the width and height of the view, For example,

int height = yourView.getLayoutParams().height;
int width = yourView.getLayoutParams().width;

This gives the converted value of the view which specified in the XML layout.

Say if the specified value for height is 53dp in XML, you will get the converted value in integer as 80.

Splitting dataframe into multiple dataframes

You can use the groupby command, if you already have some labels for your data.

 out_list = [group[1] for group in in_series.groupby(label_series.values)]

Here's a detailed example:

Let's say we want to partition a pd series using some labels into a list of chunks For example, in_series is:

2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00    1.16
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 5, dtype: float64

And its corresponding label_series is:

2019-07-01 08:00:00   1
2019-07-01 08:02:00   1
2019-07-01 08:04:00   2
2019-07-01 08:06:00   2
2019-07-01 08:08:00   2
Length: 5, dtype: float64

Run

out_list = [group[1] for group in in_series.groupby(label_series.values)]

which returns out_list a list of two pd.Series:

[2019-07-01 08:00:00   -0.10
2019-07-01 08:02:00   1.16
Length: 2, dtype: float64,
2019-07-01 08:04:00    0.69
2019-07-01 08:06:00   -0.81
2019-07-01 08:08:00   -0.64
Length: 3, dtype: float64]

Note that you can use some parameters from in_series itself to group the series, e.g., in_series.index.day

SVN 405 Method Not Allowed

I encountered the same issue and was able to fix it by:

  1. Copy the folder to another place.
  2. Delete .svn from copied folder
  3. Right click the original folder and select 'SVN Checkout'
  4. If you can't find (3), then your case is different than mine.
  5. See if the directory on the REPO-BROWSER is correct. For my case, this was the cause.
  6. Check out
  7. Get back the files from the copied folder into the original directory.
  8. Commit.

Is there a W3C valid way to disable autocomplete in a HTML form?

Here is a good article from the MDC which explains the problems (and solutions) to form autocompletion. Microsoft has published something similar here, as well.

To be honest, if this is something important to your users, 'breaking' standards in this way seems appropriate. For example, Amazon uses the 'autocomplete' attribute quite a bit, and it seems to work well.

If you want to remove the warning entirely, you can use JavaScript to apply the attribute to browsers that support it (IE and Firefox are the important browsers) using someForm.setAttribute( "autocomplete", "off" ); someFormElm.setAttribute( "autocomplete", "off" );

Finally, if your site is using HTTPS, IE automatically turns off autocompletion (as do some other browsers, as far as I know).

Update

As this answer still gets quite a few upvotes, I just wanted to point out that in HTML5, you can use the 'autocomplete' attribute on your form element. See the documentation on W3C for it.

NameError: global name 'xrange' is not defined in Python 3

You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.


If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

try:
    # Python 2
    xrange
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

try:
    # Python 2 forward compatibility
    range = xrange
except NameError:
    pass

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

What is the best alternative IDE to Visual Studio

Zeus.

Here's an example showing code completion, taken from the Zeus homepage.

example.cs open in Zeus, showing code-completion

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

Get request URL in JSP which is forwarded by Servlet

To get the current path from within the JSP file you can simply do one of the following:

<%= request.getContextPath() %>
<%= request.getRequestURI() %>
<%= request.getRequestURL() %>

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.

For that need to add the 2021 partition into that table

ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS

How do I get the different parts of a Flask request's url?

you should try:

request.url 

It suppose to work always, even on localhost (just did it).

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

In addition to Tony's answer, if you are looking to find out where your PL/SQL program is spending it's time, it is also worth checking out this part of the Oracle PL/SQL documentation.

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

This should be able to set to whatever keybindings you want for indent/outdent here:

Menu FilePreferencesKeyboard Shortcuts

editor.action.indentLines

editor.action.outdentLines

Fatal error: unexpectedly found nil while unwrapping an Optional values

I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.

First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )

I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.

var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).

So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.

Im guesssing your label should always be there?

So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.

Getting the ID of the element that fired an event

var buttons = document.getElementsByTagName('button');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++){
    buttons[i].addEventListener('click', clickResponse, false);
};
function clickResponse(){
    // do something based on button selection here...
    alert(this.id);
}

Working JSFiddle here.

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

How to remove error about glyphicons-halflings-regular.woff2 not found

This problem happens because IIS does not know about woff and woff2 file mime types.

Solution 1:

Add these lines in your web.config project:

 <system.webServer>
  ...
  </modules>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>

Solution 2:

On IIS project page:

Step 1: Go to your project IIS home page and double click on MIME Types button:

Step 1

Step 2: Click on Add button from Actions menu: Step 2

Step 3: In the middle of the screen appears a window and in this window you need to add the two lines from solution 1: Step 3

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

The requested URL /about was not found on this server

I got the same issue. My home page can be accessed but the article just not found on the server.

Go to cpanel file manager > public_html and delete .htaccess.

Then go to permalink setting in WordPress, set the permalink to whatever you want, then save. viola everything back to normal.

This issue occurred after I updated WordPress.

pop/remove items out of a python tuple

In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.

Just use

popped = unpopped[:-1]

Remember that it's an immutable, so you will have to reassign the value if you want it to change

my_tuple = my_tuple[:-1]

Example

>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)

How can I add a hint text to WPF textbox?

I accomplish this with a VisualBrush and some triggers in a Style suggested by :sellmeadog.

<TextBox>
        <TextBox.Style>
            <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
                <Style.Resources>
                    <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
                        <VisualBrush.Visual>
                            <Label Content="Search" Foreground="LightGray" />
                        </VisualBrush.Visual>
                    </VisualBrush>
                </Style.Resources>
                <Style.Triggers>
                    <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                        <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                    </Trigger>
                    <Trigger Property="Text" Value="{x:Null}">
                        <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                    </Trigger>
                    <Trigger Property="IsKeyboardFocused" Value="True">
                        <Setter Property="Background" Value="White" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>

@sellmeadog :Application running, bt Design not loading...the following Error comes: Ambiguous type reference. A type named 'StaticExtension' occurs in at least two namespaces, 'MS.Internal.Metadata.ExposedTypes.Xaml' and 'System.Windows.Markup'. Consider adjusting the assembly XmlnsDefinition attributes. 'm using .net 3.5

Pandas conditional creation of a series/dataframe column

You can use pandas methods where and mask:

df['color'] = 'green'
df['color'] = df['color'].where(df['Set']=='Z', other='red')
# Replace values where the condition is False

or

df['color'] = 'red'
df['color'] = df['color'].mask(df['Set']=='Z', other='green')
# Replace values where the condition is True

Output:

  Type Set  color
1    A   Z  green
2    B   Z  green
3    B   X    red
4    C   Y    red

How do I merge dictionaries together in Python?

I believe that, as stated above, using d2.update(d1) is the best approach and that you can also copy d2 first if you still need it.

Although, I want to point out that dict(d1, **d2) is actually a bad way to merge dictionnaries in general since keyword arguments need to be strings, thus it will fail if you have a dict such as:

{
  1: 'foo',
  2: 'bar'
}

How to specify multiple conditions in an if statement in javascript

Here is an alternative way to do that.

const conditionsArray = [
    condition1, 
    condition2,
    condition3,
]

if (conditionsArray.indexOf(false) === -1) {
    "do somthing"
}

Or ES6

if (!conditionsArray.includes(false)) {
   "do somthing"
}

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

Python Progress Bar

It is quite straightforward in Python3:

   import time
   import math

    def show_progress_bar(bar_length, completed, total):
        bar_length_unit_value = (total / bar_length)
        completed_bar_part = math.ceil(completed / bar_length_unit_value)
        progress = "*" * completed_bar_part
        remaining = " " * (bar_length - completed_bar_part)
        percent_done = "%.2f" % ((completed / total) * 100)
        print(f'[{progress}{remaining}] {percent_done}%', end='\r')

    bar_length = 30
    total = 100
    for i in range(0, total + 1):
        show_progress_bar(bar_length, i, total)
        time.sleep(0.1)

    print('\n')

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

For me changing createLBPHFaceRecognizer() to

recognizer = cv2.face.LBPHFaceRecognizer_create()

fixed the problem

How to measure elapsed time

From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

How do I get the position selected in a RecyclerView?

@Override
public void onClick(View v) {
     int pos = getAdapterPosition();
}

Simple as that, on ViewHolder

What is the best way to give a C# auto-property an initial value?

In addition to the answer already accepted, for the scenario when you want to define a default property as a function of other properties you can use expression body notation on C#6.0 (and higher) for even more elegant and concise constructs like:

public class Person{

    public string FullName  => $"{First} {Last}"; // expression body notation

    public string First { get; set; } = "First";
    public string Last { get; set; } = "Last";
}

You can use the above in the following fashion

    var p = new Person();

    p.FullName; // First Last

    p.First = "Jon";
    p.Last = "Snow";

    p.FullName; // Jon Snow

In order to be able to use the above "=>" notation, the property must be read only, and you do not use the get accessor keyword.

Details on MSDN

How can I close a dropdown on click outside?

A better version for @Tony great solution:

@Component({})
class SomeComponent {
    @ViewChild('container') container;
    @ViewChild('dropdown') dropdown;

    constructor() {
        document.addEventListener('click', this.offClickHandler.bind(this)); // bind on doc
    }

    offClickHandler(event:any) {
        if (!this.container.nativeElement.contains(event.target)) { // check click origin

            this.dropdown.nativeElement.closest(".ourDropdown.open").classList.remove("open");

        }
    }
}

In a css file: //NOT needed if you use bootstrap drop-down.

.ourDropdown{
   display: none;
}
.ourDropdown.open{
   display: inherit;
}

Remove an item from a dictionary when its key is unknown

The dict.pop(key[, default]) method allows you to remove items when you know the key. It returns the value at the key if it removes the item otherwise it returns what is passed as default. See the docs.'

Example:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

select2 - hiding the search box

You can try this

$('#select_id').select2({ minimumResultsForSearch: -1 });

it closes the search results box and then set control unvisible

You can check here in select2 document select2 documents

Permanently Set Postgresql Schema Path

Josh is correct but he left out one variation:

ALTER ROLE <role_name> IN DATABASE <db_name> SET search_path TO schema1,schema2;

Set the search path for the user, in one particular database.

How to justify a single flexbox item (override justify-content)

To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start in their behavior but have the last item justify-content: flex-end

_x000D_
_x000D_
.container {
  height: 100px;
  border: solid 10px skyblue;
  display: flex;
  justify-content: flex-end;
}

.container > *:not(:last-child) {
    margin-right: 0;
    margin-left: 0;
}

/* set the second to last-child */
.container > :nth-last-child(2) {
    margin-right: auto;
    margin-left: 0;
}

.block {
  width: 50px;
  background: tomato;
  border: 1px solid black;
}
_x000D_
<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
_x000D_
_x000D_

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

How do I instantiate a Queue object in java?

Queue in Java is defined as an interface and many ready-to-use implementation is present as part of JDK release. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, ConcurrentLinkedQueue, Linked Transfer Queue, Synchronous Queue etc.

SO You can create any of these class and hold it as Queue reference. for example

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

 public static void main (String[] args) {
  Queue que = new LinkedList();
  que.add("first");
  que.offer("second");
  que.offer("third");
  System.out.println("Queue Print:: " + que);
  
  String head = que.element();
  System.out.println("Head element:: " + head);
  
  String element1 = que.poll();
  System.out.println("Removed Element:: " + element1);
  
  System.out.println("Queue Print after poll:: " + que);
  String element2 = que.remove();
  System.out.println("Removed Element:: " + element2);
  
  System.out.println("Queue Print after remove:: " + que);  
 }
}

You can also implement your own custom Queue implementing Queue interface.

Does swift have a trim method on String?

You can also send characters that you want to be trimed

extension String {


    func trim() -> String {

        return self.trimmingCharacters(in: .whitespacesAndNewlines)

    }

    func trim(characterSet:CharacterSet) -> String {

        return self.trimmingCharacters(in: characterSet)

    }
}

validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ","))

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Why is Android Studio reporting "URI is not registered"?

Select appropriate flavour in Build Variants.

If you are viewing a particular file under Flavour1, select that flavor in BuildVariants window.

If your IDE is Android Studio (3.2.1 as of this writing), you should find Build Variants window on the lower left, aligned vertically.

Change GridView row color based on condition

\\loop throgh all rows of the grid view  

if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value1")
{
   GridView1.Rows[i - 1].ForeColor = Color.Black;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value2")
{
   GridView1.Rows[i - 1].ForeColor = Color.Blue;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value3")
{
   GridView1.Rows[i - 1].ForeColor = Color.Red;
}
else if (GridView1.Rows[i - 1].Cells[4].Text.ToString() == "value4")
{
   GridView1.Rows[i - 1].ForeColor = Color.Green;
}

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

How do I remove the "extended attributes" on a file in Mac OS X?


Answer (Individual Files)


1. Showcase keys to use in selection.

xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

2. Pick a Key to delete.

xattr -d com.apple.lastuseddate#PS ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
xattr -d kMDItemIsScreenCapture ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

3. Showcase keys again to see they have been removed.

xattr -l ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

4. Lastly, REMOVE ALL keys for a particular file

xattr -c ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png

Answer (All Files In A Directory)


1. Showcase keys to use in selection.

xattr -r ~/Desktop

2. Remove a Specific Key for EVERY FILE in a directory

xattr -rd com.apple.FinderInfo ~/Desktop

3. Remove ALL keys on EVERY FILE in a directory

xattr -rc ~/Desktop

WARN: Once you delete these you DON'T get them back!
FAULT ERROR: There is NO UNDO.


Errors


I wanted to address the error's people are getting. Because the errors drove me nuts too... On a mac if you install xattr in python, then your environment may have an issue.

There are two different paths on my mac for xattr

type -a xattr

    # xattr is /usr/local/bin/xattr    # PYTHON Installed Version
    # xattr is /usr/bin/xattr          # Mac OSX Installed Version

So in one of the example's where -c will not work in xargs is because in bash you default to the non-python version.

Works with -c

/usr/bin/xattr -c

Does NOT Work with -c

/usr/local/bin/xattr -c
    # option -c not recognized

My Shell/Terminal defaults to /usr/local/bin/xattr because my $PATH /usr/local/bin: is before /usr/bin: which I believe is the default.

I can prove this because, if you try to uninstall the python xattr you will see:

pip3 uninstall xattr
Uninstalling xattr-0.9.6:
  Would remove:
    /usr/local/bin/xattr
    /usr/local/lib/python3.7/site-packages/xattr-0.9.6.dist-info/*
    /usr/local/lib/python3.7/site-packages/xattr/*
Proceed (y/n)?

Workarounds


To Fix option -c not recognized Errors.

  1. Uninstall any Python xattr you may have: pip3 uninstall xattr
  2. Close all Terminal windows & quit Terminal
  3. Reopen a new Terminal window.
  4. ReRun xattr command and it should now work.

OR

If you want to keep the Python xattr then use

/usr/bin/xattr

for any Shell commands in Terminal


Example:


Python's version of xattr doesn't handle images at all:

Good-Mac:~ JayRizzo$ xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # Traceback (most recent call last):
    #   File "/usr/local/bin/xattr", line 8, in <module>
    #     sys.exit(main())
    #   File "/usr/local/lib/python3.7/site-packages/xattr/tool.py", line 196, in main
    #     attr_value = attr_value.decode('utf-8')
    # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 2: invalid start byte

Good-Mac:~ JayRizzo$ /usr/bin/xattr ~/Desktop/screenshot\ 2019-10-23\ at\ 010212.png
    # com.apple.FinderInfo
    # com.apple.lastuseddate#PS
    # com.apple.metadata:kMDItemIsScreenCapture
    # com.apple.metadata:kMDItemScreenCaptureGlobalRect
    # com.apple.metadata:kMDItemScreenCaptureType

Man Pages

MAN PAGE for OSX xattr

MAN PAGE for Python xattr VERSION 0.6.4

NOTE: I could not find the python help page for current VERSION 0.9.6

Thanks for Reading!

Resizing SVG in html?

I have found it best to add viewBox and preserveAspectRatio attributes to my SVGs. The viewbox should describe the full width and height of the SVG in the form 0 0 w h:

<svg preserveAspectRatio="xMidYMid meet" viewBox="0 0 700 550"></svg>

Run jQuery function onclick

There's several things you can improve upon here. To start, there's no reason to use an <a> (anchor) tag since you don't have a link.

Every element can be bound to click and hover events... divs, spans, labels, inputs, etc.

I can't really identify what it is you're trying to do, though. You're mixing the goal with your own implementation and, from what I've seen so far, you're not really sure how to do it. Could you better illustrate what it is you're trying to accomplish?

== EDIT ==

The requirements are still very vague. I've implemented a very quick version of what I'm imagining you're saying ... or something close that illustrates how you might be able to do it. Left me know if I'm on the right track.

http://jsfiddle.net/THEtheChad/j9Ump/

Adjust list style image position?

Another workaround is just to set the li item to flex or inline-flex. Depending on the circumstances that may suit you better. In case you have a real icon / image placed in the HTML the default flex position is on the central horizontal line.

How do I format a Microsoft JSON date?

Using the jQuery UI datepicker - really only makes sense if you're already including jQuery UI:

$.datepicker.formatDate('MM d, yy', new Date(parseInt('/Date(1224043200000)/'.substr(6)))); 

output:

October 15, 2008

Scripting Language vs Programming Language

To understand the difference between a scripting language and a programming language, one has to understand why scripting languages were born.

Initially, there were programming languages that was written to build programs like excel, word, browsers, games and etc. These programs were built with languages like c and java. Overtime, these programs needed a way for users to create new functionality, so they had to provide an interface to their bytecode and hence scripting languages were born.

A scripting language usually isnt compiled so can run as soon as you write something meaningful. Hence excel may be built using C++ but it exposes a scripting language called VBA for users to define functionality. Similarly browsers may be built with C++/Java but they expose a scripting language called javascript (not related to java in any way). Games, are usually built with C++ but expose a language called Lua for users to define custom functionality.

A scripting language usually sits behind some programming language. Scripting languages usually have less access to the computers native abilities since they run on a subset of the original programming language. An example here is that Javascript will not be able to access your file system. Scripting languages are usually slower than programming languages.

Although scripting languages may have less access and are slower, they can be very powerful tools. One factor attributing to a scripting languages success is the ease of updating. Do you remember the days of java applets on the web, this is an example of running a programming language (java) vs running a scripting language (javascript). At the time, computers were not as powerful and javascript wasn't as mature so Java applets dominated the scenes. But Java applets were annoying, they required the user to sort of load and compile the language. Fast forward to today, Java applets are almost extinct and Javascript dominates the scene. Javascript is extremely fast to load since most of the browser components have been installed already.

Lastly, scripting languages are also considered programming languages (although some people refuse to accept this) - the term we should be using here is scripting languages vs compiled languages.

Create an array or List of all dates between two dates

LINQ:

Enumerable.Range(0, 1 + end.Subtract(start).Days)
          .Select(offset => start.AddDays(offset))
          .ToArray(); 

For loop:

var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
   dates.Add(dt);
}

EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:

var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date) 
                                               ? timeSeries[date] : defaultValue);

Using CMake with GNU Make: How can I see the exact commands?

Or simply export VERBOSE environment variable on the shell like this: export VERBOSE=1

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

If you are on Windows 7, simply run Eclipse with Admin privilege will solve this issue.

Just tried this on my Windows 7 64bits OS.

Why should I use var instead of a type?

When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.

There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.

If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

You can try to host the analytics.js locally and update it's contents with a caching script or manually.

The js file is updated only few times a year and if you don't need any new tracking features update it manually.

https://developers.google.com/analytics/devguides/collection/analyticsjs/changelog

How do you extract classes' source code from a dll file?

You can use dotPeek The only thing I have to say is that when using it, right-click on the class to select Decompiled Source instead of double-clicking, otherwise dotpeek will only display the contents of the local cs file, not the decompiled content. Option instance

Update Eclipse with Android development tools v. 23

I have followed instructions found here and tried to fix my old Eclipse + SDK + ADT, but with no luck. The basic problem keeps beeing the same; I still get the error message:

This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.

But my eclipse can't find updates and can't install ADT 23 as new software. So I can't compile my old project in my workspace.

I tested a fresh eclipode bundle for Windows 8, followed instructions found from Android's developers page, step by step, and it worked fine. So it seems that the Windows Eclipse build is not broken. But I wan't use my Linux installation, my old Ubuntu 10. It seems obvious, that to getting the Linux Eclipse environment working again, I must install a new Eclipse bundle, my old Eclipse won't ever see updates for ADT 23 to get things working. Again, these intructions are for Linux developers that wan't to get their old workspace projects working again without changes in the developing environment, except you must install a new Eclipse bundle, but after that your projects will work as well as before the version 23 SDK/ADT-mess.

  1. If you are an Android developer you want to be sure, that you developing environment won't be messed up. Backup:
    • ~./android (Here are your developer keys)
    • Your old SDK dirrectory
    • Your workspace
  2. Download the Eclipse bundle, Get the Android SDK.
  3. Follow instructions, create directory ~/Development and unzip bundle there. You get Eclipse and SDK directories.
  4. Start Eclipse from that directory
  5. Eclipse asks for a workspace. You can give it the old one.
  6. In Eclipse settings set SDK as downloaded SDK.
  7. Start Android SDK manager and download tools, Android versions you use and extras said in the Android developer tool page instructions
  8. You should now be ready to compile your old projects again, but for me it was not that simple. My old projects had errors. So open problems windows and you get to know that annotation.jar is missing. So you must copy annotations.jar from your old SDK, from, the backup you made, or from the older sdk.zip explained in this thread to <new SDK>/tools/support/annotations.jar

After that I could use my old workspace in Ubuntu and compile and launch applications to Android devices. It was that simple. Thanks Google ;-(

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

'Syntax Error: invalid syntax' for no apparent reason

If you are running the program with python, try running it with python3.

Java: get greatest common divisor

As far as I know, there isn't any built-in method for primitives. But something as simple as this should do the trick:

public int gcd(int a, int b) {
   if (b==0) return a;
   return gcd(b,a%b);
}

You can also one-line it if you're into that sort of thing:

public int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); }

It should be noted that there is absolutely no difference between the two as they compile to the same byte code.

Hide/Show Action Bar Option Menu Item for different fragments

Even though the question is old and answered. There is a simpler answer to that than the above mentioned. You don't need to use any other variables. You can create the buttons on action bar whatever the fragment you want, instead of doing the visibility stuff(show/hide).

Add the following in the fragment whatever u need the menu item.

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Sample menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_addFlat"
        android:icon="@drawable/add"
        android:showAsAction="ifRoom|withText"
        android:title="@string/action_addFlat"/>
</menu>

Handling onclick events is as usual.

href image link download on click

No, it isn't. You will need something on the server to send a Content-Disposition header to set the file as an attachment instead of being inline. You could do this with plain Apache configuration though.

I've found an example of doing it using mod_rewrite, although I know there is a simpler way.

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

PHP equivalent of .NET/Java's toString()

You are looking for strval:

string strval ( mixed $var )

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format().

Regular Expression Match to test for a valid year

In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.

Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.

This will work for exact matching using non-capturing groups:

(?:19|20)\d{2}

Bootstrap Dropdown menu is not working

For Bootstrap 4 you need an additional library. If you read your browser console, Bootstrap will actually print an error message telling you that you need it for drop down to work.

Error: Bootstrap dropdown require Popper.js (https://popper.js.org)

Ignore outliers in ggplot2 boxplot

If you want to force the whiskers to extend to the max and min values, you can tweak the coef argument. Default value for coef is 1.5 (i.e. default length of the whiskers is 1.5 times the IQR).

# Load package and create a dummy data frame with outliers 
#(using example from Ramnath's answer above)
library(ggplot2)
df = data.frame(y = c(-100, rnorm(100), 100))

# create boxplot that includes outliers
p0 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)))

# create boxplot where whiskers extend to max and min values
p1 = ggplot(df, aes(y = y)) + geom_boxplot(aes(x = factor(1)), coef = 500)

image of p0

image of p1

Returning Promises from Vuex actions

Actions

ADD_PRODUCT : (context,product) => {
  return Axios.post(uri, product).then((response) => {
    if (response.status === 'success') {  
      context.commit('SET_PRODUCT',response.data.data)
    }
    return response.data
  });
});

Component

this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
  if (res.status === 'success') {
    // write your success actions here....
  } else {
     // write your error actions here...
  }
})

Get bytes from std::string in C++

Normally, encryption functions take

encrypt(const void *ptr, size_t bufferSize);

as arguments. You can pass c_str and length directly:

encrypt(strng.c_str(), strng.length());

This way, extra space is allocated or wasted.

How to change the blue highlight color of a UITableViewCell?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView" enter image description here

How to Call VBA Function from Excel Cells?

Here's the answer

Steps to follow:

  1. Open the Visual Basic Editor. In Excel, hit Alt+F11 if on Windows, Fn+Option+F11 if on a Mac.

  2. Insert a new module. From the menu: Insert -> Module (Don't skip this!).

  3. Create a Public function. Example:

    Public Function findArea(ByVal width as Double, _
                             ByVal height as Double) As Double
        ' Return the area
        findArea = width * height
    End Function
    
  4. Then use it in any cell like you would any other function: =findArea(B12,C12).

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

C# with MySQL INSERT parameters

I had the same issue -- Finally tried the ? sigil instead of @, and it worked.

According to the docs:

Note. Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

Really? Why don't you just throw an exception if someone tries to use the so called old syntax? A few hours down the drain for a 20 line program...

MySQL::MySQLCommand

java Arrays.sort 2d array

To sort in descending order you can flip the two parameters

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (b, a) -> Integer.compare(a[0], b[0]));

Output:

13, 5
12, 100
12, 85
1, 5

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

Regular expression that matches valid IPv6 addresses

InetAddressUtils has all the patterns defined. I ended-up using their pattern directly, and am pasting it here for reference:

private static final String IPV4_BASIC_PATTERN_STRING =
        "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
         "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255

private static final Pattern IPV4_PATTERN =
    Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");

private static final Pattern IPV4_MAPPED_IPV6_PATTERN = // TODO does not allow for redundant leading zeros
        Pattern.compile("^::[fF]{4}:" + IPV4_BASIC_PATTERN_STRING + "$");

private static final Pattern IPV6_STD_PATTERN =
    Pattern.compile(
            "^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$");

private static final Pattern IPV6_HEX_COMPRESSED_PATTERN =
    Pattern.compile(
            "^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)" + // 0-6 hex fields
             "::" +
             "(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$"); // 0-6 hex fields 

Program "make" not found in PATH

Just to clarify the details that Adel's linked eclipse forum covers, here's how I solved this (on OS X):

Note: for me, even though my personal environment (i.e. if in bash, echo $PATH) had /Developer/usr/bin in it, I still had to add it to Eclipse's Environment variables:

Go to Eclipse Preferences -> C/C++ -> Build -> Environment -> Add.. -> "${PATH}:/Developer/usr/bin"

In the case of some other OS, just use the right path where make exists.

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

When tracing out variables in the console, How to create a new line?

Why not just use separate console.log() for each var, and separate with a comma rather than converting them all to strings? That would give you separate lines, AND give you the true value of each variable rather than the string representation of each (assuming they may not all be strings).

console.log('roleName',roleName);
console.log('role_ID',role_ID);
console.log('modal_ID',modal_ID);
console.log('related',related);

And I think it would be easier to read/maintain.

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

how to check if the input is a number or not in C?

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}

How to cut first n and last n columns?

You can use Bash for that:

while read -a cols; do echo ${cols[@]:0:1} ${cols[@]:1,-1}; done < file.txt

Delete all objects in a list

To delete all objects in a list, you can directly write list = []

Here is example:

>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.

C:\Python25\Lib\idlelib\idle.pyw

Calculate a MD5 hash from a string

public static string Md5(string input, bool isLowercase = false)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] byteHash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                string hash = BitConverter.ToString(byteHash).Replace("-", "");
                return (isLowercase) ? hash.ToLower() : hash;
            }
        }

Scala vs. Groovy vs. Clojure

Obviously, the syntax are completely different (Groovy is closest to Java), but I suppose that is not what you are asking for.

If you are interested in using them to script a Java application, Scala is probably not a good choice, as there is no easy way to evaluate it from Java, whereas Groovy is especially suited for that purpose.

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

How do I detect if software keyboard is visible on Android Device or not?

In Android you can detect through ADB shell. I wrote and use this method:

{
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession("<userName>", "<IP>", 22);
            session.setPassword("<Password>");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            BufferedReader in = new BufferedReader(new    
            InputStreamReader(channel.getInputStream()));
            channel.setCommand("C:/Android/android-sdk/platform-tools/adb shell dumpsys window 
            InputMethod | findstr \"mHasSurface\"");
            channel.connect();

            String msg = null;
            String msg2 = " mHasSurface=true";

            while ((msg = in.readLine()) != null) {
                Boolean isContain = msg.contains(msg2);
                log.info(isContain);
                if (isContain){
                    log.info("Hiding keyboard...");
                    driver.hideKeyboard();
                }
                else {
                    log.info("No need to hide keyboard.");
                }
            }

            channel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

EventListener Enter Key

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}

Regex to check whether a string contains only numbers

Simple Regex javascript

var cnpj = "12.32.432/1-22";
var rCnpj = cnpj.replace(/\D/gm,"");
console.log(cnpj);

*Result:

1232432122

Checks for only numbers:

if(rCnpj === cnpj){
   return true;
}

Simple example

if("12.32.432/1-22".replace(/\D/gm,"").length > 0){
   console.log("Ok.");
}

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

jQuery: Get height of hidden element in jQuery

Building further on user Nick's answer and user hitautodestruct's plugin on JSBin, I've created a similar jQuery plugin which retrieves both width and height and returns an object containing these values.

It can be found here: http://jsbin.com/ikogez/3/

Update

I've completely redesigned this tiny little plugin as it turned out that the previous version (mentioned above) wasn't really usable in real life environments where a lot of DOM manipulation was happening.

This is working perfectly:

/**
 * getSize plugin
 * This plugin can be used to get the width and height from hidden elements in the DOM.
 * It can be used on a jQuery element and will retun an object containing the width
 * and height of that element.
 *
 * Discussed at StackOverflow:
 * http://stackoverflow.com/a/8839261/1146033
 *
 * @author Robin van Baalen <[email protected]>
 * @version 1.1
 * 
 * CHANGELOG
 *  1.0 - Initial release
 *  1.1 - Completely revamped internal logic to be compatible with javascript-intense environments
 *
 * @return {object} The returned object is a native javascript object
 *                  (not jQuery, and therefore not chainable!!) that
 *                  contains the width and height of the given element.
 */
$.fn.getSize = function() {    
    var $wrap = $("<div />").appendTo($("body"));
    $wrap.css({
        "position":   "absolute !important",
        "visibility": "hidden !important",
        "display":    "block !important"
    });

    $clone = $(this).clone().appendTo($wrap);

    sizes = {
        "width": $clone.width(),
        "height": $clone.height()
    };

    $wrap.remove();

    return sizes;
};

Compare two MySQL databases

I use a piece of software called Navicat to :

  • Sync Live databases to my test databases.
  • Show differences between the two databases.

It costs money, it's windows and mac only, and it's got a whacky UI, but I like it.

How to get the part of a file after the first line that matches a regular expression?

The following will print the line matching TERMINATE till the end of the file:

sed -n -e '/TERMINATE/,$p'

Explained: -n disables default behavior of sed of printing each line after executing its script on it, -e indicated a script to sed, /TERMINATE/,$ is an address (line) range selection meaning the first line matching the TERMINATE regular expression (like grep) to the end of the file ($), and p is the print command which prints the current line.

This will print from the line that follows the line matching TERMINATE till the end of the file:
(from AFTER the matching line to EOF, NOT including the matching line)

sed -e '1,/TERMINATE/d'

Explained: 1,/TERMINATE/ is an address (line) range selection meaning the first line for the input to the 1st line matching the TERMINATE regular expression, and d is the delete command which delete the current line and skip to the next line. As sed default behavior is to print the lines, it will print the lines after TERMINATE to the end of input.

Edit:

If you want the lines before TERMINATE:

sed -e '/TERMINATE/,$d'

And if you want both lines before and after TERMINATE in 2 different files in a single pass:

sed -e '1,/TERMINATE/w before
/TERMINATE/,$w after' file

The before and after files will contain the line with terminate, so to process each you need to use:

head -n -1 before
tail -n +2 after

Edit2:

IF you do not want to hard-code the filenames in the sed script, you can:

before=before.txt
after=after.txt
sed -e "1,/TERMINATE/w $before
/TERMINATE/,\$w $after" file

But then you have to escape the $ meaning the last line so the shell will not try to expand the $w variable (note that we now use double quotes around the script instead of single quotes).

I forgot to tell that the new line is important after the filenames in the script so that sed knows that the filenames end.


Edit: 2016-0530

Sébastien Clément asked: "How would you replace the hardcoded TERMINATE by a variable?"

You would make a variable for the matching text and then do it the same way as the previous example:

matchtext=TERMINATE
before=before.txt
after=after.txt
sed -e "1,/$matchtext/w $before
/$matchtext/,\$w $after" file

to use a variable for the matching text with the previous examples:

## Print the line containing the matching text, till the end of the file:
## (from the matching line to EOF, including the matching line)
matchtext=TERMINATE
sed -n -e "/$matchtext/,\$p"
## Print from the line that follows the line containing the 
## matching text, till the end of the file:
## (from AFTER the matching line to EOF, NOT including the matching line)
matchtext=TERMINATE
sed -e "1,/$matchtext/d"
## Print all the lines before the line containing the matching text:
## (from line-1 to BEFORE the matching line, NOT including the matching line)
matchtext=TERMINATE
sed -e "/$matchtext/,\$d"

The important points about replacing text with variables in these cases are:

  1. Variables ($variablename) enclosed in single quotes ['] won't "expand" but variables inside double quotes ["] will. So, you have to change all the single quotes to double quotes if they contain text you want to replace with a variable.
  2. The sed ranges also contain a $ and are immediately followed by a letter like: $p, $d, $w. They will also look like variables to be expanded, so you have to escape those $ characters with a backslash [\] like: \$p, \$d, \$w.

Enter key pressed event handler

You can also use PreviewKeyDown in WPF:

<TextBox PreviewKeyDown="EnterClicked" />

or in C#:

myTextBox.PreviewKeyDown += EnterClicked;

And then in the attached class:

void EnterClicked(object sender, KeyEventArgs e) {
    if(e.Key == Key.Return) {
        DoSomething();
        e.Handled = true;
    }
}

apc vs eaccelerator vs xcache

It may be important to point out the current stable, unstable and dev versions of each (including date):

APC

http://pecl.php.net/package/apc

dev        dev          2013-09-12
3.1.14     beta         2013-01-02
3.1.9      stable       2011-05-14

Xcache

http://xcache.lighttpd.net/

dev/3.2     dev        2013-12-13
dev/3.1     dev        2013-11-05
3.1.0       stable     2013-10-10
3.0.4       stable     2013-10-10

eAccelerator

https://github.com/eaccelerator/eaccelerator

dev         dev        2012-08-16
0.9.6-rc1   unstable   2010-01-26
0.9.5.1     stable     2007-05-16

How to get request URI without context path?

getPathInfo() sometimes return null. In documentation HttpServletRequest

This method returns null if there was no extra path information.

I need get path to file without context path in Filter and getPathInfo() return me null. So I use another method: httpRequest.getServletPath()

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String newPath = parsePathToFile(httpRequest.getServletPath());
    ...

}

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest:

  DigestInfo ::= SEQUENCE {
      digestAlgorithm AlgorithmIdentifier,
      digest OCTET STRING
  }

Which is why the encryption by the Cipher and Signature are different.

Javascript change font color

Try like this:

var clr = 'green';
var html = '<font color="' + clr + '">' + onlineff + ' </font>';

This being said, you should avoid using the <font> tag. It is now deprecated. Use CSS to change the style (color) of a given element in your markup.

Possible to view PHP code of a website?

By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).

Finding the median of an unsorted array

It can be done using Quickselect Algorithm in O(n), do refer to Kth order statistics (randomized algorithms).

Get size of an Iterable in Java

java 8 and above

StreamSupport.stream(data.spliterator(), false).count();

How to convert int to float in python?

You can literally convert it into float using:


float_value = float(integer_value)

Likewise, you can convert an integer back to float datatype with:


integer_value = int(float_value)

Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html

how to display excel sheet in html page

Upload your file to Skydrive and then right click and select "Embed". They will provide iframe snippet which you can paste in your html. This works flawlessly.

Source: Office.com

jQuery: Performing synchronous AJAX requests

As you're making a synchronous request, that should be

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

Example - http://api.jquery.com/jQuery.ajax/#example-3

PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

Chrome:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Firefox:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

Build a simple HTTP server in C

An HTTP server is conceptually simple:

  • Open port 80 for listening
  • When contact is made, gather a little information (get mainly - you can ignore the rest for now)
  • Translate the request into a file request
  • Open the file and spit it back at the client

It gets more difficult depending on how much of HTTP you want to support - POST is a little more complicated, scripts, handling multiple requests, etc.

But the base is very simple.

Combine two integer arrays

Here a simple function that use variable arguments:

final static
public int[] merge(final int[] ...arrays ) {
    int size = 0;
    for ( int[] a: arrays )
        size += a.length;

        int[] res = new int[size];

        int destPos = 0;
        for ( int i = 0; i < arrays.length; i++ ) {
            if ( i > 0 ) destPos += arrays[i-1].length;
            int length = arrays[i].length;
            System.arraycopy(arrays[i], 0, res, destPos, length);
        }

        return res;
}

To use:

int[] array1 = {1,2,3};
int[] array2 = {4,5,6};
int[] array3 = {7,8,9};
int[] array1and2and3 = merge(array1, array2, array3);
for ( int x: array1and2and3 ) 
    System.out.print( String.format("%3d", x) );

Get href attribute on jQuery

var a_href = $('div.cpt').find('h2 a').attr('href');

should be

var a_href = $(this).find('div.cpt').find('h2 a').attr('href');

In the first line, your query searches the entire document. In the second, the query starts from your tr element and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

Make Font Awesome icons in a circle?

With Font Awesome you can easily use stacked icons like this:

<span class="fa-stack fa-2x">
  <i class="fas fa-circle-thin fa-stack-2x"></i>
  <i class="fas fa-lock fa-stack-1x fa-inverse"></i>
</span>

refer Font Awesome Stacked Icons

Update:- Fiddle for stacked icons

jQuery select by attribute using AND and OR operators

AND operation

a=$('[myc="blue"][myid="1"][myid="3"]');

OR operation, use commas

a=$('[myc="blue"],[myid="1"],[myid="3"]');

As @Vega commented:

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

c - warning: implicit declaration of function ‘printf’

You need to include the appropriate header

#include <stdio.h>

If you're not sure which header a standard function is defined in, the function's man page will state this.

VBScript: Using WScript.Shell to Execute a Command Line Program That Accesses Active Directory

Taking Shiraz's idea and running with it...

In your application, are you explicitly defining a domain User Account and Password to access AD?

When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.

A VBScript example would be as follows:

  Dim objConnection As ADODB.Connection
    Set objConnection = CreateObject("ADODB.Connection")
    objConnection.Provider = "ADsDSOObject"
    objConnection.Properties("User ID") = "MyDomain\MyAccount"
    objConnection.Properties("Password") = "MyPassword"
    objConnection.Open "Active Directory Provider"

If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.

Java, how to compare Strings with String Arrays

import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

Client to send SOAP request and receive response

I think there is a simpler way:

 public async Task<string> CreateSoapEnvelope()
 {
      string soapString = @"<?xml version=""1.0"" encoding=""utf-8""?>
          <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
              <soap:Body>
                  <HelloWorld xmlns=""http://tempuri.org/"" />
              </soap:Body>
          </soap:Envelope>";

          HttpResponseMessage response = await PostXmlRequest("your_url_here", soapString);
          string content = await response.Content.ReadAsStringAsync();

      return content;
 }

 public static async Task<HttpResponseMessage> PostXmlRequest(string baseUrl, string xmlString)
 {
      using (var httpClient = new HttpClient())
      {
          var httpContent = new StringContent(xmlString, Encoding.UTF8, "text/xml");
          httpContent.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld");

          return await httpClient.PostAsync(baseUrl, httpContent);
       }
 }

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Remove querystring from URL

(() => {
        'use strict';
        const needle = 'SortOrder|Page'; // example
        if ( needle === '' || needle === '{{1}}' ) { 
            return; 
        }           
        const needles = needle.split(/\s*\|\s*/);
        const querystripper = ev => {
                    if (ev) { window.removeEventListener(ev.type, querystripper, true);}
                    try {
                          const url = new URL(location.href);
                          const params = new URLSearchParams(url.search.slice(1));
                          for (const needleremover of needles) {
                                if (params.has(needleremover)) {
                                url.searchParams.delete(needleremover);
                                    window.location.href = url;
                            }
                          }     
                    } catch (ex) { }
        };          
        if (document.readyState === 'loading') {
                 window.addEventListener('DOMContentLoaded', querystripper, true);
        } else {
                 querystripper();
        }
})();

That's how I did it, also has RegEx support.

How can I take a screenshot with Selenium WebDriver?

Ruby

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")

More file types and options are available and you can see them in file takes_screenshot.rb.

C: convert double to float, preserving decimal point precision

A float generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.

How can I get the IP address from NIC in Python?

Find the IP address of the first eth/wlan entry in ifconfig that's RUNNING:

import itertools
import os
import re

def get_ip():
    f = os.popen('ifconfig')
    for iface in [' '.join(i) for i in iter(lambda: list(itertools.takewhile(lambda l: not l.isspace(),f)), [])]:
        if re.findall('^(eth|wlan)[0-9]',iface) and re.findall('RUNNING',iface):
            ip = re.findall('(?<=inet\saddr:)[0-9\.]+',iface)
            if ip:
                return ip[0]
    return False

How to tell whether a point is to the right or left side of a line

@AVB's answer in ruby

det = Matrix[
  [(x2 - x1), (x3 - x1)],
  [(y2 - y1), (y3 - y1)]
].determinant

If det is positive its above, if negative its below. If 0, its on the line.

What's the difference between tilde(~) and caret(^) in package.json?

~ fixes major and minor numbers. It is used when you're ready to accept bug-fixes in your dependency, but don't want any potentially incompatible changes.

^ fixes the major number only. It is used when you're closely watching your dependencies and are ready to quickly change your code if minor release will be incompatible.

In addition to that, ^ is not supported by old npm versions, and should be used with caution.

So, ^ is a good default, but it's not perfect. I suggest to carefully pick and configure the semver operator that is most useful to you.

Rerender view on browser resize with React

This code is using the new React context API:

  import React, { PureComponent, createContext } from 'react';

  const { Provider, Consumer } = createContext({ width: 0, height: 0 });

  class WindowProvider extends PureComponent {
    state = this.getDimensions();

    componentDidMount() {
      window.addEventListener('resize', this.updateDimensions);
    }

    componentWillUnmount() {
      window.removeEventListener('resize', this.updateDimensions);
    }

    getDimensions() {
      const w = window;
      const d = document;
      const documentElement = d.documentElement;
      const body = d.getElementsByTagName('body')[0];
      const width = w.innerWidth || documentElement.clientWidth || body.clientWidth;
      const height = w.innerHeight || documentElement.clientHeight || body.clientHeight;

      return { width, height };
    }

    updateDimensions = () => {
      this.setState(this.getDimensions());
    };

    render() {
      return <Provider value={this.state}>{this.props.children}</Provider>;
    }
  }

Then you can use it wherever you want in your code like this:

<WindowConsumer>
  {({ width, height }) =>  //do what you want}
</WindowConsumer>

How can I use pointers in Java?

All java objects are pointer because a variable which holds address is called pointer and object hold address.so object is pointer variable.

How can I reload .emacs after changing it?

I suggest that you don't do this, initially. Instead, start a new emacs session and test whatever changes you made to see if they work correctly. The reason to do it this way is to avoid leaving you in a state where you have an inoperable .emacs file, which fails to load or fails to load cleanly. If you do all of your editing in the original session, and all of your testing in a new session, you'll always have something reliable to comment out offending code.

When you are finally happy with your changes, then go ahead and use one of the other answers to re-load. My personal preference is to eval just the section you've added/changed, and to do that just highlight the region of added/changed code and call M-x eval-region. Doing that minimizes the code that's evaluated, minimizing any unintentional side-effects, as luapyad points out.

How to save password when using Subversion from the console

Just to emphasize what Tomasz Gandor and Domain said about having the right version of svn and that it was compiled to enable plain text password storage, you need verify what you have:

svn --version
svn, version 1.9.7 (r1800392)
...
WARNING: Plaintext password storage is enabled!
...

The following authentication credential caches are available:

* Plaintext cache in /gr/home/ffvdqb/.subversion
* GPG-Agent

Versus:

svn --version
svn, version 1.12.2 (r1863366)
...

The following authentication credential caches are available:

* Gnome Keyring
* GPG-Agent
* KWallet (KDE)

Once you see that your version of svn was enabled for plain text password storage, then apply all the rest of the answers here.

Is there a wikipedia API just for retrieve content summary?

Yes, there is. For example, if you wanted to get the content of the first section of the article Stack Overflow, use a query like this:

http://en.wikipedia.org/w/api.php?format=xml&action=query&prop=revisions&titles=Stack%20Overflow&rvprop=content&rvsection=0&rvparse

The parts mean this:

  • format=xml: Return the result formatter as XML. Other options (like JSON) are available. This does not affect the format of the page content itself, only the enclosing data format.

  • action=query&prop=revisions: Get information about the revisions of the page. Since we don't specify which revision, the latest one is used.

  • titles=Stack%20Overflow: Get information about the page Stack Overflow. It's possible to get the text of more pages in one go, if you separate their names by |.

  • rvprop=content: Return the content (or text) of the revision.

  • rvsection=0: Return only content from section 0.

  • rvparse: Return the content parsed as HTML.

Keep in mind that this returns the whole first section including things like hatnotes (“For other uses …”), infoboxes or images.

There are several libraries available for various languages that make working with API easier, it may be better for you if you used one of them.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If the ActiveDirectory module is present add

import-module activedirectory

before your code.

To check if exist try:

get-module -listavailable

ActiveDirectory module is default present in windows server 2008 R2, install it in this way:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

For have it to work you need at least one DC in the domain as windows 2008 R2 and have Active Directory Web Services (ADWS) installed on it.

For Windows Server 2008 read here how to install it

How to kill MySQL connections

In MySQL Workbench:

Left-hand side navigator > Management > Client Connections

It gives you the option to kill queries and connections.

Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here

How do I change a tab background color when using TabLayout?

Add atribute in xml:

<android.support.design.widget.TabLayout
    ....
    app:tabBackground="@drawable/tab_color_selector"
    ...
    />

And create in drawable folder, tab_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
    <item android:drawable="@color/tab_background_unselected"/>
</selector>

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

How to disable phone number linking in Mobile Safari?

Add this, I think it is what you're looking for:

<meta name = "format-detection" content = "telephone=no">

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace secure_password_store
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

How do I test a single file using Jest?

We are using nrwl-nx with Angular. In this case we can use this command:

npm test <ng-project> -- --testFile "file-name-part"

Notes:

  • npm test will run the test script specified in package.json: "test": "ng test"
  • Thus the rest of the cmd will be passed to ng test
    • <ng-project> is the name of a project in angular.json
      • when you omit this parameter, the "defaultProject" (specified in angular.json) will be used (so you must specify it, when the test is not in your default project)
    • Next we must check which builder is used:
      • In angular.json navigate to "project" - "<ng-project>" - "architect" - "test"
      • and check the "builder", which in our case is: "@nrwl/jest:jest"
    • Now that we know the builder, we need to find the available cmd-line parameters
      • On the command line, run npm test <ng-project> -- --help to see all available options
      • Or check the online documentation
    • One of the options is --testFile which is used here

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

Try catch statements in C

Ok, I couldn't resist replying to this. Let me first say I don't think it's a good idea to simulate this in C as it really is a foreign concept to C.

We can use abuse the preprocessor and local stack variables to give use a limited version of C++ try/throw/catch.

Version 1 (local scope throws)

#include <stdbool.h>

#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;

Version 1 is a local throw only (can't leave the function's scope). It does rely on C99's ability to declare variables in code (it should work in C89 if the try is first thing in the function).

This function just makes a local var so it knows if there was an error and uses a goto to jump to the catch block.

For example:

#include <stdio.h>
#include <stdbool.h>

#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;

int main(void)
{
    try
    {
        printf("One\n");
        throw();
        printf("Two\n");
    }
    catch(...)
    {
        printf("Error\n");
    }
    return 0;
}

This works out to something like:

int main(void)
{
    bool HadError=false;
    {
        printf("One\n");
        HadError=true;
        goto ExitJmp;
        printf("Two\n");
    }
ExitJmp:
    if(HadError)
    {
        printf("Error\n");
    }
    return 0;
}

Version 2 (scope jumping)

#include <stdbool.h>
#include <setjmp.h>

jmp_buf *g__ActiveBuf;

#define try jmp_buf __LocalJmpBuff;jmp_buf *__OldActiveBuf=g__ActiveBuf;bool __WasThrown=false;g__ActiveBuf=&__LocalJmpBuff;if(setjmp(__LocalJmpBuff)){__WasThrown=true;}else
#define catch(x) g__ActiveBuf=__OldActiveBuf;if(__WasThrown)
#define throw(x) longjmp(*g__ActiveBuf,1);

Version 2 is a lot more complex but basically works the same way. It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch.

The example expanded again:

jmp_buf *g_ActiveBuf;

int main(void)
{
    jmp_buf LocalJmpBuff;
    jmp_buf *OldActiveBuf=g_ActiveBuf;
    bool WasThrown=false;
    g_ActiveBuf=&LocalJmpBuff;

    if(setjmp(LocalJmpBuff))
    {
        WasThrown=true;
    }
    else
    {
        printf("One\n");
        longjmp(*g_ActiveBuf,1);
        printf("Two\n");
    }
    g_ActiveBuf=OldActiveBuf;
    if(WasThrown)
    {
        printf("Error\n");
    }
    return 0;
}

This uses a global pointer so the longjmp() knows what try was last run. We are using abusing the stack so child functions can also have a try/catch block.

Using this code has a number of down sides (but is a fun mental exercise):

  • It will not free allocated memory as there are no deconstructors being called.
  • You can't have more than 1 try/catch in a scope (no nesting)
  • You can't actually throw exceptions or other data like in C++
  • Not thread safe at all
  • You are setting up other programmers for failure because they will likely not notice the hack and try using them like C++ try/catch blocks.

How to change JAVA.HOME for Eclipse/ANT

In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable. Instead it is set to the home directory of the project's JRE.

To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.

To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab. Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.

If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

How to select all the columns of a table except one column?

Without creating new table you can do simply (e.g with mysqli):

  1. get all columns
  2. loop through all columns and remove wich you want
  3. make your query

$r = mysqli_query('SELECT column_name FROM information_schema.columns WHERE table_name = table_to_query');

$c = count($r); while($c--) if($r[$c]['column_name'] != 'column_to_remove_from_query') $a[] = $r[$c]['column_name']; else unset($r[$c]);

$r = mysqli_query('SELECT ' . implode(',', $a) . ' FROM table_to_query');

Best way to store a key=>value array in JavaScript?

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

How can I dynamically add a directive in AngularJS?

Josh David Miller is correct.

PCoelho, In case you're wondering what $compile does behind the scenes and how HTML output is generated from the directive, please take a look below

The $compile service compiles the fragment of HTML("< test text='n' >< / test >") that includes the directive("test" as an element) and produces a function. This function can then be executed with a scope to get the "HTML output from a directive".

var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);

More details with full code samples here: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs

What is the recommended project structure for spring boot rest projects?

I have an example which I have been using for couple years. Please take a look as a reference.

https://github.com/bigzidane/springboot-rest-h2-swagger

How do I raise the same Exception with a custom message in Python?

Try below:

try:
    raise ValueError("Original message. ")
except Exception as err:
    message = 'My custom error message. '
    # Change the order below to "(message + str(err),)" if custom message is needed first. 
    err.args = (str(err) + message,)
    raise 

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 try:
----> 2     raise ValueError("Original message")
      3 except Exception as err:
      4     message = 'My custom error message.'
      5     err.args = (str(err) + ". " + message,)

ValueError: Original message. My custom error message.

Is there a replacement for unistd.h for Windows (Visual C)?

Try including the io.h file. It seems to be the Visual Studio's equivalent of unistd.h.

I hope this helps.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to export JavaScript array info to csv (on client side)?

I added to Xavier Johns function to also include the field headers if needed, uses jQuery though. The $.each bit will need changing for a native javascript loop

function exportToCsv(filename, rows, headers = false) {
    var processRow = function (row) {
        row = $.map(row, function(value, index) {
            return [value];
        });
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            if(i == 0 && j == 0 && headers == true){
                var ii = 0;
                $.each(rows[i], function( index, value ) {
                    //console.log(index);
                    var fieldName = index === null ? '' : index.toString();
                    //console.log(fieldName);
                    var fieldResult = fieldName.replace(/"/g, '""');
                    //console.log(fieldResult);
                    if (fieldResult.search(/("|,|\n)/g) >= 0){
                        fieldResult = '"' + fieldResult + '"';
                    }
                    //console.log(fieldResult);
                    if (ii > 0){
                        finalVal += ',';
                        finalVal += fieldResult;
                    }else{
                        finalVal += fieldResult;
                    }
                    ii++;
                    //console.log(finalVal);
                });
                finalVal += '\n';
                //console.log('end: '+finalVal);
            }
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0){
                result = '"' + result + '"';
            }
            if (j > 0){
                finalVal += ',';
                finalVal += result;
            }else{
                finalVal += result;
            }
        }
        return finalVal + '\n';
    };
    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }
    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    }else{
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

How to type ":" ("colon") in regexp?

In most regex implementations (including Java's), : has no special meaning, neither inside nor outside a character class.

Your problem is most likely due to the fact the - acts as a range operator in your class:

[A-Za-z0-9.,-:]*

where ,-: matches all ascii characters between ',' and ':'. Note that it still matches the literal ':' however!

Try this instead:

[A-Za-z0-9.,:-]*

By placing - at the start or the end of the class, it matches the literal "-". As mentioned in the comments by Keoki Zee, you can also escape the - inside the class, but most people simply add it at the end.

A demo:

public class Test {
    public static void main(String[] args) {
        System.out.println("8:".matches("[,-:]+"));      // true: '8' is in the range ','..':'
        System.out.println("8:".matches("[,:-]+"));      // false: '8' does not match ',' or ':' or '-'
        System.out.println(",,-,:,:".matches("[,:-]+")); // true: all chars match ',' or ':' or '-'
    }
}

Create request with POST, which response codes 200 or 201 and content

The idea is that the response body gives you a page that links you to the thing:

201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI.

This means that you would include a Location in the response header that gives the URL of where you can find the newly created thing:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597

Response body

They then go on to mention what you should include in the response body:

The 201 response payload typically describes and links to the resource(s) created.

For the human using the browser, you give them something they can look at, and click, to get to their newly created resource:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: text/html

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

If the page will only be used by a robot, the it makes sense to have the response be computer readable:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/xml

<createdResources>
   <questionID>1860645</questionID>
   <answerID>36373586</answerID>
   <primary>/a/36373586/12597</primary>
   <additional>
      <resource>http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586</resource>
      <resource>http://stackoverflow.com/a/1962757/12597</resource>
   </additional>
</createdResource>

Or, if you prefer:

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/36373586/12597
Content-Type: application/json

{ 
   "questionID": 1860645, 
   "answerID": 36373586,
   "primary": "/a/36373586/12597",
   "additional": [
      "http://stackoverflow.com/questions/1860645/create-request-with-post-which-response-codes-200-or-201-and-content/36373586#36373586",
      "http://stackoverflow.com/a/36373586/12597"
   ]
}

The response is entirely up to you; it's arbitrarily what you'd like.

Cache friendly

Finally there's the optimization that I can pre-cache the created resource (because I already have the content; I just uploaded it). The server can return a date or ETag which I can store with the content I just uploaded:

See Section 7.2 for a discussion of the meaning and purpose of validator header fields, such as ETag and Last-Modified, in a 201 response.

HTTP/1.1 201 Created
Date: Sat, 02 Apr 2016 12:22:40 GMT
Location: http://stackoverflow.com/a/23704283/12597
Content-Type: text/html
ETag: JF2CA53BOMQGU5LTOQQGC3RAMV4GC3LQNRSS4
Last-Modified: Sat, 02 Apr 2016 12:22:39 GMT 

Your answer has been saved! 
Click <A href="/a/36373586/12597">here</A> to view it.

And ETag s are purely arbitrary values. Having them be different when a resource changes (and caches need to be updated) is all that matters. The ETag is usually a hash (e.g. SHA2). But it can be a database rowversion, or an incrementing revision number. Anything that will change when the thing changes.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

I solved the problem updating all packages from Android SDK Manager and also, I had to install Extras -> Android Support Repository.

How to change pivot table data source in Excel?

Just figured it out-click anywhere in the table, then go to the tabs at the top of the page and select Options-from there you'll see a Change Data Source selection.

Most recent previous business day in Python

This will give a generator of working days, of course without holidays, stop is datetime.datetime object. If you need holidays just make additional argument with list of holidays and check with 'IFology' ;-)

def workingdays(stop, start=datetime.date.today()):
    while start != stop:
        if start.weekday() < 5:
            yield start
        start += datetime.timedelta(1)

Later on you can count them like

workdays = workingdays(datetime.datetime(2015, 8, 8))
len(list(workdays))

How do I assert my exception message with JUnit Test annotation?

I like the @Rule answer. However, if for some reason you don't want to use rules. There is a third option.

@Test (expected = RuntimeException.class)
public void myTestMethod()
{
   try
   {
      //Run exception throwing operation here
   }
   catch(RuntimeException re)
   {
      String message = "Employee ID is null";
      assertEquals(message, re.getMessage());
      throw re;
    }
    fail("Employee Id Null exception did not throw!");
  }

Using Python's list index() method on a list of tuples or objects?

I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:

Using the enumerator method to match on sub-indices in a list of tuples. e.g.

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
        ('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

    # if index is a tuple of subindices to match against:
    for pos,k in enumerate(li):
        match = True
        for i in indices:
            if k[i] != vals[i]:
                match = False
                break;
        if (match):
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals)    # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals)    # = 4

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I am using Windows 7 Professional and I was having same problem @Bayu Mohammad Lufty not worked for me.

I simply delete .AndroidStudio1.2 from my C:\Users\UserName\ and restart my Android studio again. It open Android Studio perfectly! It configured everything again in next start :)

How to animate the change of image in an UIImageView?

Try this:

_imageView.image = image;
[_imageView.layer addAnimation:[CATransition animation] forKey:kCATransition];

Converting string to Date and DateTime

Use strtotime() on your first date then date('Y-m-d') to convert it back:

$time = strtotime('10/16/2003');

$newformat = date('Y-m-d',$time);

echo $newformat;
// 2003-10-16

Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

How to set Default Controller in asp.net MVC 4 & MVC 5

Set below code in RouteConfig.cs in App_Start folder

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}

IF still not working then do below steps

Second Way : You simple follow below steps,

1) Right click on your Project

2) Select Properties

3) Select Web option and then Select Specific Page (Controller/View) and then set your login page

Here, Account is my controller and Login is my action method (saved in Account Controller)

Please take a look attachedenter image description here screenshot.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

A new version of OSX or XCode was installed and Apple wants you to agree to their Terms and Conditions. So just launch Xcode and "Agree" to them.

Javascript require() function giving ReferenceError: require is not defined

By default require() is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.

Truncate a SQLite table if it exists?

Just do delete. This is from the SQLite documentation:

The Truncate Optimization

"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

How to capture and save an image using custom camera in Android?

please see below answer.

Custom_CameraActivity.java

public class Custom_CameraActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mCameraPreview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);

        Button captureButton = (Button) findViewById(R.id.button_capture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, mPicture);
            }
        });
    }

    /**
     * Helper method to access the camera returns null if it cannot get the
     * camera or does not exist
     * 
     * @return
     */
    private Camera getCameraInstance() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // cannot get camera or does not exist
        }
        return camera;
    }

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }
}

CameraPreview.java

public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mCamera.stopPreview();
        mCamera.release();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
            int width, int height) {
        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Capture" />

</LinearLayout>

Add Below Lines to your androidmanifest.xml file

<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to insert data into elasticsearch

To test and try curl requests from Windows, you can make use of Postman client Chrome extension. It is very simple to use and quite powerful.

Or as suggested you can install the cURL util.

A sample curl request is as follows.

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"user" : "Arun Thundyill Saseendran",
"post_date" : "2009-03-23T12:30:00",
"message" : "trying out Elasticsearch"
}' "http://10.103.102.56:9200/sampleindex/sampletype/"

I am also getting started with and exploring ES in vast. So please let me know if you have any other doubts.

EDIT: Updated the index name and type name to be fully lowercase to avoid errors and follow convention.

How to set background color of view transparent in React Native

Try this backgroundColor: '#00000000' it will set background color to transparent, it follows #rrggbbaa hex codes

Querying DynamoDB by date

Approach I followed to solve this problem is by created a Global Secondary Index as below. Not sure if this is the best approach but hopefully if it is useful to someone.

Hash Key                 | Range Key
------------------------------------
Date value of CreatedAt  | CreatedAt

Limitation imposed on the HTTP API user to specify the number of days to retrieve data, defaulted to 24 hr.

This way, I can always specify the HashKey as Current date's day and RangeKey can use > and < operators while retrieving. This way the data is also spread across multiple shards.

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to convert an object to a byte array in C#

This worked for me:

byte[] bfoo = (byte[])foo;

foo is an Object that I'm 100% certain that is a byte array.

What are libtool's .la file for?

It is a textual file that includes a description of the library.

It allows libtool to create platform-independent names.

For example, libfoo goes to:

Under Linux:

/lib/libfoo.so       # Symlink to shared object
/lib/libfoo.so.1     # Symlink to shared object
/lib/libfoo.so.1.0.1 # Shared object
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library

Under Cygwin:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # libtool library
/bin/cygfoo_1.dll    # DLL

Under Windows MinGW:

/lib/libfoo.dll.a    # Import library
/lib/libfoo.a        # Static library
/lib/libfoo.la       # 'libtool' library
/bin/foo_1.dll       # DLL

So libfoo.la is the only file that is preserved between platforms by libtool allowing to understand what happens with:

  • Library dependencies
  • Actual file names
  • Library version and revision

Without depending on a specific platform implementation of libraries.

Make xargs execute the command once for each line of input

@Draemon answers seems to be right with "-0" even with space in the file.

I was trying the xargs command and I found that "-0" works perfectly with "-L". even the spaces are treated (if input was null terminated ). the following is an example :

#touch "file with space"
#touch "file1"
#touch "file2"

The following will split the nulls and execute the command on each argument in the list :

 #find . -name 'file*' -print0 | xargs -0 -L1
./file with space
./file1
./file2

so -L1 will execute the argument on each null terminated character if used with "-0". To see the difference try :

 #find . -name 'file*' -print0 | xargs -0 | xargs -L1
 ./file with space ./file1 ./file2

even this will execute once :

 #find . -name 'file*' -print0  | xargs -0  | xargs -0 -L1
./file with space ./file1 ./file2

The command will execute once as the "-L" now doesn't split on null byte. you need to provide both "-0" and "-L" to work.

Specified argument was out of the range of valid values. Parameter name: site

This occurred to me when I applied the 2017 Fall Creator Update. I was able to resolve by repairing IIS 10.0 Express (I do not have IIS installed on my box.)

Note: As a user pointed out in the comments,

Repair can be found in "Programs and Features" - the "classic" control panel.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Data truncated for column?

Your problem is that at the moment your incoming_Cid column defined as CHAR(1) when it should be CHAR(34).

To fix this just issue this command to change your columns' length from 1 to 34

ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);

Here is SQLFiddle demo

SQL Error: ORA-00913: too many values

The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

Parsing CSV files in C#, with header

This code reads csv to DataTable:

public static DataTable ReadCsv(string path)
{
    DataTable result = new DataTable("SomeData");
    using (TextFieldParser parser = new TextFieldParser(path))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        bool isFirstRow = true;
        //IList<string> headers = new List<string>();

        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            if (isFirstRow)
            {
                foreach (string field in fields)
                {
                    result.Columns.Add(new DataColumn(field, typeof(string)));
                }
                isFirstRow = false;
            }
            else
            {
                int i = 0;
                DataRow row = result.NewRow();
                foreach (string field in fields)
                {
                    row[i++] = field;
                }
                result.Rows.Add(row);
            }
        }
    }
    return result;
}

How to check Oracle database for long running queries

v$session_longops

If you look for sofar != totalwork you'll see ones that haven't completed, but the entries aren't removed when the operation completes so you can see a lot of history there too.