Programs & Examples On #Windows server 2008 x64

for questions specifically about the x64 version of Windows Server 2008.

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

A tool to use here is awk:

cat file | awk 'BEGIN{ found=0} /TERMINATE/{found=1}  {if (found) print }'

How does this work:

  1. We set the variable 'found' to zero, evaluating false
  2. if a match for 'TERMINATE' is found with the regular expression, we set it to one.
  3. If our 'found' variable evaluates to True, print :)

The other solutions might consume a lot of memory if you use them on very large files.

Combine Regexp?

Will the conditions be ORed or ANDed together?

Starts with: abc
Ends with: xyz
Contains: 123
Doesn't contain: 456

The OR version is fairly simple; as you said, it's mostly a matter of inserting pipes between individual conditions. The regex simply stops looking for a match as soon as one of the alternatives matches.

/^abc|xyz$|123|^(?:(?!456).)*$/

That fourth alternative may look bizarre, but that's how you express "doesn't contain" in a regex. By the way, the order of the alternatives doesn't matter; this is effectively the same regex:

/xyz$|^(?:(?!456).)*$|123|^abc/

The AND version is more complicated. After each individual regex matches, the match position has to be reset to zero so the next regex has access to the whole input. That means all of the conditions have to be expressed as lookaheads (technically, one of them doesn't have to be a lookahead, I think it expresses the intent more clearly this way). A final .*$ consummates the match.

/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/

And then there's the possibility of combined AND and OR conditions--that's where the real fun starts. :D

Making a cURL call in C#

I know this is a very old question but I post this solution in case it helps somebody. I recently met this problem and google led me here. The answer here helps me to understand the problem but there are still issues due to my parameter combination. What eventually solves my problem is curl to C# converter. It is a very powerful tool and supports most of the parameters for Curl. The code it generates is almost immediately runnable.

How to use getJSON, sending data with post method?

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

My code looked like this:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');

C compiling - "undefined reference to"?

seems you need to link with the obj file that implements tolayer5()

Update: your function declaration doesn't match the implementation:

      void tolayer5(int AorB, struct msg msgReceived)
      void tolayer5(int, char data[])

So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

Select SQL results grouped by weeks

Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'

Select  ProductName,
        IsNull([1],0) as 'Week 1',
        IsNull([2],0) as 'Week 2',
        IsNull([3],0) as 'Week 3',
        IsNull([4],0) as 'Week 4',
        IsNull([5], 0) as 'Week 5'
From 
(
Select  ProductName,
        DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
        Sale as 'Sale'
From dbo.WeekReport

-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p 
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv

OUTPUT LOOK LIKE THIS

a   0   0   0   0   20
b   0   0   0   0   4
c   0   0   0   0   3

href around input type submit

It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).

To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).

How do I undo the most recent local commits in Git?

enter image description here

Assuming you're working in Visual Studio, if you go in to you branch history and look at all of your commits, simply select the event prior to the commit you want to undo, right-click it, and select Revert. Easy as that.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Since I don't believe "Please use..." plus some random code that is unrelated to the question is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.

When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES

Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES
                          ('col1', 'col3', 'col2')

It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.

Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.

TLDR

using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x => 
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));

This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.

Use jQuery to change an HTML tag?

I noticed that the first answer wasn't quite what I needed, so I made a couple of modifications and figured I'd post it back here.

Improved replaceTag(<tagName>)

replaceTag(<tagName>, [withDataAndEvents], [withDataAndEvents])

Arguments:

  • tagName: String
    • The tag name e.g. "div", "span", etc.
  • withDataAndEvents: Boolean
    • "A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well." info
  • deepWithDataAndEvents: Boolean,
    • A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false)." info

Returns:

A newly created jQuery element

Okay, I know there are a few answers here now, but I took it upon myself to write this again.

Here we can replace the tag in the same way we use cloning. We are following the same syntax as .clone() with the withDataAndEvents and deepWithDataAndEvents which copy the child nodes' data and events if used.

Example:

$tableRow.find("td").each(function() {
  $(this).clone().replaceTag("li").appendTo("ul#table-row-as-list");
});

Source:

$.extend({
    replaceTag: function (element, tagName, withDataAndEvents, deepWithDataAndEvents) {
        var newTag = $("<" + tagName + ">")[0];
        // From [Stackoverflow: Copy all Attributes](http://stackoverflow.com/a/6753486/2096729)
        $.each(element.attributes, function() {
            newTag.setAttribute(this.name, this.value);
        });
        $(element).children().clone(withDataAndEvents, deepWithDataAndEvents).appendTo(newTag);
        return newTag;
    }
})
$.fn.extend({
    replaceTag: function (tagName, withDataAndEvents, deepWithDataAndEvents) {
        // Use map to reconstruct the selector with newly created elements
        return this.map(function() {
            return jQuery.replaceTag(this, tagName, withDataAndEvents, deepWithDataAndEvents);
        })
    }
})

Note that this does not replace the selected element, it returns the newly created one.

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

Count with IF condition in MySQL query

Better still (or shorter anyway):

SUM(ccc_news_comments.id = 'approved')

This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)

As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().

How to change the font color of a disabled TextBox?

Just handle Enable changed and set it to the color you need

private void TextBoxName_EnabledChanged(System.Object sender, System.EventArgs e)
{
    ((TextBox)sender).ForeColor = Color.Black;
}

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had this issue too because I was filtering /src/main/resources and forgot I had added a keystore (*.jks) binary to this directory.

Add a "resource" block with exclusions for binary files and your problem may be resolved.

<build>
  <finalName>somename</finalName>
  <testResources>
    <testResource>
      <directory>src/test/resources</directory>
      <filtering>false</filtering>
    </testResource>
  </testResources>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
      <excludes>
        <exclude>*.jks</exclude>
        <exclude>*.png</exclude>
      </excludes>        
    </resource>
  </resources>
...

Difference between decimal, float and double in .NET?

For applications such as games and embedded systems where memory and performance are both critical, float is usually the numeric type of choice as it is faster and half the size of a double. Integers used to be the weapon of choice, but floating point performance has overtaken integer in modern processors. Decimal is right out!

How to revert initial git commit?

I will throw in what worked for me in the end. I needed to remove the initial commit on a repository as quarantined data had been misplaced, the commit had already been pushed.

Make sure you are are currently on the right branch.

git checkout master

git update-ref -d HEAD

git commit -m "Initial commit

git push -u origin master

This was able to resolve the problem.

Important

This was on an internal repository which was not publicly accessible, if your repository was publicly accessible please assume anything you need to revert has already been pulled down by someone else.

What does '?' do in C++?

This is commonly referred to as the conditional operator, and when used like this:

condition ? result_if_true : result_if_false

... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

It is syntactic sugar, and in this case, it can be replaced with

int qempty()
{ 
  if(f == r)
  {
      return 1;
  } 
  else 
  {
      return 0;
  }
}

Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.

WordPress is giving me 404 page not found for all pages except the homepage

Within the WordPress admin interface do the following:

  1. Go to admin setting

  2. Click on permalink and select post name in radio button.

  3. Scroll down and you will see .htaccess code here like.

    <IfModule mod_rewrite.c>
        RewriteRule ^index\.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /wordpress/index.php [L]
    </IfModule> 
    
  4. Copy the code and paste in the .htaccess file.

Java :Add scroll into text area

After adding JTextArea into JScrollPane here:

scroll = new JScrollPane(display);

You don't need to add it again into other container like you do:

middlePanel.add(display);

Just remove that last line of code and it will work fine. Like this:

    middlePanel=new JPanel();
    middlePanel.setBorder(new TitledBorder(new EtchedBorder(), "Display Area"));

    // create the middle panel components

    display = new JTextArea(16, 58);
    display.setEditable(false); // set textArea non-editable
    scroll = new JScrollPane(display);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

    //Add Textarea in to middle panel
    middlePanel.add(scroll);

JScrollPane is just another container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:

new JScrollPane( myComponent ) 

or set view like this:

JScrollPane pane = new JScrollPane ();
pane.getViewport ().setView ( myComponent );

Additional:

Here is fully working example since you still did not get it working:

public static void main ( String[] args )
{
    JPanel middlePanel = new JPanel ();
    middlePanel.setBorder ( new TitledBorder ( new EtchedBorder (), "Display Area" ) );

    // create the middle panel components

    JTextArea display = new JTextArea ( 16, 58 );
    display.setEditable ( false ); // set textArea non-editable
    JScrollPane scroll = new JScrollPane ( display );
    scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );

    //Add Textarea in to middle panel
    middlePanel.add ( scroll );

    // My code
    JFrame frame = new JFrame ();
    frame.add ( middlePanel );
    frame.pack ();
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}

And here is what you get: enter image description here

Java JRE 64-bit download for Windows?

You can also just search on sites like Tucows and CNET, they have it there too.

JavaScript is in array

You can try below code. Check http://api.jquery.com/jquery.grep/

var blockedTile = new Array("118", "67", "190", "43", "135", "520");
var searchNumber = "11878";
arr = jQuery.grep(blockedTile, function( i ) {
  return i === searchNumber;
});
if(arr.length){ console.log('Present'); }else{ console.log('Not Present'); }

check arr.length if it's more than 0 means string is present else it's not present.

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

    public static void main(String[] args) throws Exception
    {

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

CodeIgniter - File upload required validation

CodeIgniter file upload optionally ...works perfectly..... :)

---------- controller ---------

function file()
{
 $this->load->view('includes/template', $data);
}

function valid_file()
{
 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 {
    $this->file();
 }
 else
 {
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  {
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    {
        return false;
    }

  }
  else
  {
    return true;
  }
}

i just use this lines which makes it optionally,

if($_FILES['userfile']['error'] != 4)
{
 return false;
}

$_FILES['userfile']['error'] != 4 is for file required to upload.

you can make it unnecessary by using $_FILES['userfile']['error'] != 4, then it will pass this error for file required and works great with other types of errors if any by using return false , hope it works for u ....

How to automate browsing using python?

There are plenty of built in python modules that whould help with this. For example urllib and htmllib.

The problem will be simpler if you change the way you're approaching it. You say you want to "fill some forms, click submit button, send the data back to server, recieve the response", which sounds like a four stage process.

In fact, what you need to do is post some data to a webserver and get a response.

This is as simple as:

>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()

(example taken from the urllib docs).

What you do with the response depends on how complex the HTML is and what you want to do with it. You might get away with parsing it using a regular expression or two, or you can use the htmllib.HTMLParser class, or maybe a higher level more flexible parser like Beautiful Soup.

Should I declare Jackson's ObjectMapper as a static field?

com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)

com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
  com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
     com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
        com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
           com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
              com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
                 com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
                    com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)

The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.

May be another reason to avoid a static ObjectMapper

What does an exclamation mark mean in the Swift language?

ASK YOURSELF

  • Does the type person? have an apartment member/property? OR
  • Does the type person have an apartment member/property?

If you can't answer this question, then continue reading:

To understand you may need super-basic level of understanding of Generics. See here. A lot of things in Swift are written using Generics. Optionals included

The code below has been made available from this Stanford video. Highly recommend you to watch the first 5 minutes

An Optional is an enum with only 2 cases

enum Optional<T>{
    case None
    case Some(T)
}

let x: String? = nil //actually means:

let x = Optional<String>.None

let x :String? = "hello" //actually means:

let x = Optional<String>.Some("hello")

var y = x! // actually means:

switch x {
case .Some(let value): y = value
case .None: // Raise an exception
}

Optional binding:

let x:String? = something
if let y = x {
    // do something with y
}
//Actually means:

switch x{
case .Some(let y): print)(y) // or whatever else you like using 
case .None: break
}

when you say var john: Person? You actually mean such:

enum Optional<Person>{
case .None
case .Some(Person)
}

Does the above enum have any property named apartment? Do you see it anywhere? It's not there at all! However if you unwrap it ie do person! then you can ... what it does under the hood is : Optional<Person>.Some(Person(name: "John Appleseed"))


Had you defined var john: Person instead of: var john: Person? then you would have no longer needed to have the ! used, because Person itself does have a member of apartment


As a future discussion on why using ! to unwrap is sometimes not recommended see this Q&A

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.

So try to download other versions of PostgreSQL and get all the components

Show div when radio button selected

$('input[name=test]').click(function () {
    if (this.id == "watch-me") {
        $("#show-me").show('slow');
    } else {
        $("#show-me").hide('slow');
    }
});

http://jsfiddle.net/2SsAk/2/

Save array in mysql database

You can store the array using serialize/unserialize. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode/json_decode instead (which gives you a widely supported format). Avoid using implode/explode for this since you'll probably end up with bugs or security flaws.

Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?

Also, don't save the raw $_POST array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).

Spring-Security-Oauth2: Full authentication is required to access this resource

The client_id and client_secret, by default, should go in the Authorization header, not the form-urlencoded body.

  1. Concatenate your client_id and client_secret, with a colon between them: [email protected]:12345678.
  2. Base 64 encode the result: YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
  3. Set the Authorization header: Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==

Find the 2nd largest element in an array with minimum number of comparisons

Here is some code that might not be optimal but at least actually finds the 2nd largest element:

if( val[ 0 ] > val[ 1 ] )
{
    largest = val[ 0 ]
    secondLargest = val[ 1 ];
}
else
{
    largest = val[ 1 ]
    secondLargest = val[ 0 ];
}

for( i = 2; i < N; ++i )
{
    if( val[ i ] > secondLargest )
    {
        if( val[ i ] > largest )
        {
            secondLargest = largest;
            largest = val[ i ];
        }
        else
        {
            secondLargest = val[ i ];
        }
    }
}

It needs at least N-1 comparisons if the largest 2 elements are at the beginning of the array and at most 2N-3 in the worst case (one of the first 2 elements is the smallest in the array).

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

Do AJAX requests retain PHP Session info?

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

Scale Image to fill ImageView width and keep aspect ratio

I did something similar to the above and then banged my head against the wall for a few hours because it did not work inside a RelativeLayout. I ended up with the following code:

package com.example;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ScaledImageView extends ImageView {
    public ScaledImageView(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final Drawable d = getDrawable();

        if (d != null) {
            int width;
            int height;
            if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
                height = MeasureSpec.getSize(heightMeasureSpec);
                width = (int) Math.ceil(height * (float) d.getIntrinsicWidth() / d.getIntrinsicHeight());
            } else {
                width = MeasureSpec.getSize(widthMeasureSpec);
                height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
            }
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

And then to prevent RelativeLayout from ignoring the measured dimension I did this:

    <FrameLayout
        android:id="@+id/image_frame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/something">

        <com.example.ScaledImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="150dp"/>
    </FrameLayout>

Test a weekly cron job

sudo run-parts --test /var/spool/cron/crontabs/

files in that crontabs/ directory needs to be executable by owner - octal 700

source: man cron and NNRooth's

Writelines writes lines without newline, Just fills the file

As we have well established here, writelines does not append the newlines for you. But, what everyone seems to be missing, is that it doesn't have to when used as a direct "counterpart" for readlines() and the initial read persevered the newlines!

When you open a file for reading in binary mode (via 'rb'), then use readlines() to fetch the file contents into memory, split by line, the newlines remain attached to the end of your lines! So, if you then subsequently write them back, you don't likely want writelines to append anything!

So if, you do something like:

with open('test.txt','rb') as f: lines=f.readlines()
with open('test.txt','wb') as f: f.writelines(lines)

You should end up with the same file content you started with.

Escape a string for a sed replace pattern

Here is an example of an AWK I used a while ago. It is an AWK that prints new AWKS. AWK and SED being similar it may be a good template.

ls | awk '{ print "awk " "'"'"'"  " {print $1,$2,$3} " "'"'"'"  " " $1 ".old_ext > " $1 ".new_ext"  }' > for_the_birds

It looks excessive, but somehow that combination of quotes works to keep the ' printed as literals. Then if I remember correctly the vaiables are just surrounded with quotes like this: "$1". Try it, let me know how it works with SED.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to set background color in jquery

Try this for multiple CSS styles:

$(this).css({
    "background-color": 'red',
    "color" : "white"
});

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

Sending emails in Node.js?

Nodemailer is basically a module that gives you the ability to easily send emails when programming in Node.js. There are some great examples of how to use the Nodemailer module at http://www.nodemailer.com/. The full instructions about how to install and use the basic functionality of Nodemailer is included in this link.

I personally had trouble installing Nodemailer using npm, so I just downloaded the source. There are instructions for both the npm install and downloading the source.

This is a very simple module to use and I would recommend it to anyone wanting to send emails using Node.js. Good luck!

string sanitizer for filename

preg_replace("[^\w\s\d\.\-_~,;:\[\]\(\]]", '', $file)

Add/remove more valid characters depending on what is allowed for your system.

Alternatively you can try to create the file and then return an error if it's bad.

How do you append to a file?

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

By using append mode, the operating system will place any write at the end of the file.

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Datatable select with multiple conditions

Yes, the DataTable.Select method supports boolean operators in the same way that you would use them in a "real" SQL statement:

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");

See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select method.

Partial Dependency (Databases)

I hope this explaination gives a more intuitive appeal to dependency than the answers previously given.

Functional Dependency

An analysis of dependency operates on the attribute level, i.e. one or more attribute is determined by another attribute, it comes before the concept of keys. 'The role of a key is based on the concept of determination. 'Determination is the state in which knowing the value of one attribute makes it possible to determine the value of another.' Database Systems 12ed

Functional dependency is when one or more attributes determine one or more attributes. For instance:

Social Security Number -> First Name, Last Name.

However, by definition of functional dependency:

(SSN, First Name) -> Last Name

This is also a valid functional dependency. The determinants (The attribute that which determines another attribution) are called super key.

Full Functional Dependency

Thus, as a subset of functional dependency, there is the concept of full functional dependency, where the bare minimal determinant is considered. We refer those bare minimal determinants collectively as one candidate key (weird linguistic quirk in my opinion, like the concept of vector).

Partial Functional Dependency

However, sometimes one of the attributes in the candidate key is sufficient to determine another attribute(s), BUT not all, in a relation (a table with no rows). That, is when you have a partial functional dependency within a relation.

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

Removing "NUL" characters

Highlight a single null character, goto find replace - it usually automatically inserts the highlighted text into the find box. Enter a space into or leave blank the replace box.

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

How do I set vertical space between list items?

setting padding-bottom for each list using pseudo class is a viable method. Also line height can be used. Remember that font properties such as font-family, Font-weight, etc. plays a role for uneven heights.

Validate fields after user has left a field

based on @nicolas answer.. Pure CSS should the trick, it will only show the error message on blur

<input type="email" id="input-email" required
               placeholder="Email address" class="form-control" name="email"
               ng-model="userData.email">
        <p ng-show="form.email.$error.email" class="bg-danger">This is not a valid email.</p>

CSS

.ng-invalid:focus ~ .bg-danger {
     display:none;
}

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

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

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

Run a string as a command within a Bash script

don't put your commands in variables, just run it

matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
PWD=$(pwd)
teamAComm="$PWD/a.sh"
teamBComm="$PWD/b.sh"
include="$PWD/server_official.conf"
serverbin='/usr/local/bin/rcssserver'    
cd $matchdir
$serverbin include=$include server::team_l_start = ${teamAComm} server::team_r_start=${teamBComm} CSVSaver::save='true' CSVSaver::filename = 'out.csv'

Java 8 Lambda Stream forEach with multiple statements

In the first case alternatively to multiline forEach you can use the peek stream operation:

entryList.stream()
         .peek(entry -> entry.setTempId(tempId))
         .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));

In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

anchor jumping by using javascript

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>

Android Studio - Auto complete and other features not working

  1. Close Android Studio

  2. Go to c_users_path_on_windows/.AndroidStudio3.5/system/

  3. Delete the cache folder

  4. Start Android Studio

    This works for me.

explicit casting from super class to subclass

The code generates a compilation error because your instance type is an Animal:

Animal animal=new Animal();

Downcasting is not allowed in Java for several reasons. See here for details.

How to insert a new line in strings in Android

Try:

String str = "my string \n my other string";

When printed you will get:

my string
my other string

Difference between two dates in years, months, days in JavaScript

This code should give you desired results

//************************** Enter your dates here **********************//

var startDate = "10/05/2014";
var endDate = "11/3/2016"

//******* and press "Run", you will see the result in a popup *********//



var noofdays = 0;
var sdArr = startDate.split("/");
var startDateDay = parseInt(sdArr[0]);
var startDateMonth = parseInt(sdArr[1]);
var startDateYear = parseInt(sdArr[2]);
sdArr = endDate.split("/")
var endDateDay = parseInt(sdArr[0]);
var endDateMonth = parseInt(sdArr[1]);
var endDateYear = parseInt(sdArr[2]);

console.log(startDateDay+' '+startDateMonth+' '+startDateYear);
var yeardays = 365;
var monthArr = [31,,31,30,31,30,31,31,30,31,30,31];
var noofyears = 0
var noofmonths = 0;

if((startDateYear%4)==0) monthArr[1]=29;
else monthArr[1]=28;

if(startDateYear == endDateYear){

    noofyears = 0;
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);
   
}else{
    if(endDateMonth < startDateMonth){
        noofyears = (endDateYear - startDateYear)-1;  
    if(noofyears < 1) noofyears = 0;
  }else{
            noofyears = endDateYear - startDateYear;  
  }
    noofmonths = getMonthDiff(startDate,endDate);
    if(noofmonths < 0) noofmonths = 0;
    noofdays = getDayDiff(startDate,endDate);   
}
 
 alert(noofyears+' year, '+ noofmonths+' months, '+ noofdays+' days'); 

function getDayDiff(startDate,endDate){ 
    if(endDateDay >=startDateDay){
      noofdays = 0;
      if(endDateDay > startDateDay) {
        noofdays = endDateDay - startDateDay;
       }
     }else{
            if((endDateYear%4)==0) {
            monthArr[1]=29;
        }else{
            monthArr[1] = 28;
        }
        
        if(endDateMonth != 1)
        noofdays = (monthArr[endDateMonth-2]-startDateDay) + endDateDay;
        else
        noofdays = (monthArr[11]-startDateDay) + endDateDay;
     }
    return noofdays;
}

function getMonthDiff(startDate,endDate){
        if(endDateMonth > startDateMonth){
        noofmonths = endDateMonth - startDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
      }else{
        noofmonths = (12-startDateMonth) + endDateMonth;
        if(endDateDay < startDateDay){
                noofmonths--;
            }
     }

return noofmonths;
}

https://jsfiddle.net/moremanishk/hk8c419f/

Short circuit Array.forEach like calling break

Found this solution on another site. You can wrap the forEach in a try / catch scenario.

if(typeof StopIteration == "undefined") {
 StopIteration = new Error("StopIteration");
}

try {
  [1,2,3].forEach(function(el){
    alert(el);
    if(el === 1) throw StopIteration;
  });
} catch(error) { if(error != StopIteration) throw error; }

More details here: http://dean.edwards.name/weblog/2006/07/enum/

What is the difference between Subject and BehaviorSubject?

A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

Subject example (with RxJS 5 API):

const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));

Console output will be empty

BehaviorSubject example:

const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));

Console output: 1

In addition:

  • BehaviorSubject should be created with an initial value: new Rx.BehaviorSubject(1)
  • Consider ReplaySubject if you want the subject to hold more than one value

converting list to json format - quick and easy way

I prefer using linq-to-json feature of JSON.NET framework. Here's how you can serialize a list of your objects to json.

List<MyObject> list = new List<MyObject>();

Func<MyObject, JObject> objToJson =
    o => new JObject(
            new JProperty("ObjectId", o.ObjectId), 
            new JProperty("ObjectString", o.ObjectString));

string result = new JObject(new JArray(list.Select(objToJson))).ToString();

You fully control what will be in the result json string and you clearly see it just looking at the code. Surely, you can get rid of Func<T1, T2> declaration and specify this code directly in the new JArray() invocation but with this code extracted to Func<> it looks much more clearer what is going on and how you actually transform your object to json. You can even store your Func<> outside this method in some sort of setup method (i.e. in constructor).

Checking whether a variable is an integer or not

If the variable is entered like a string (e.g. '2010'):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

Before using this I worked it out with try/except and checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

Escaping Double Quotes in Batch Script

If the string is already within quotes then use another quote to nullify its action.

echo "Insert tablename(col1) Values('""val1""')" 

How to check if variable is array?... or something array-like

Functions

<?php

/**
 * Is Array?
 * @param mixed $x
 * @return bool
 */
function isArray($x) : bool {
  return !isAssociative($x);
}

/**
 * Is Associative Array?
 * @param mixed $x
 * @return bool
 */
function isAssociative($x) : bool {
  if (!is_array($array)) {
    return false;
  }
  $i = count($array);
  while ($i > 0) {
    if (!isset($array[--$i])) {
      return true;
    }
  }
  return false;
}

Example

<?php

$arr = [ 'foo', 'bar' ];
$obj = [ 'foo' => 'bar' ];

var_dump(isAssociative($arr));
# bool(false)

var_dump(isAssociative($obj));
# bool(true)

var_dump(isArray($obj));
# bool(false)

var_dump(isArray($arr));
# bool(true)

Why can I not push_back a unique_ptr into a vector?

std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
 std::unique_ptr<int>]'

The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

The following works with the new emplace calls.

std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );

See using unique_ptr with standard library containers for further reading.

How can I check if an element exists in the visible DOM?

All existing elements have parentElement set, except the HTML element!

function elExists (e) { 
    return (e.nodeName === 'HTML' || e.parentElement !== null);
};

Commit only part of a file in Git

git gui provides this functionality under the diff view. Just right click the line(s) you're interested in and you should see a "stage this line to commit" menu item.

Get file name from URL

import java.io.*;

import java.net.*;

public class ConvertURLToFileName{


   public static void main(String[] args)throws IOException{
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Please enter the URL : ");

   String str = in.readLine();


   try{

     URL url = new URL(str);

     System.out.println("File : "+ url.getFile());
     System.out.println("Converting process Successfully");

   }  
   catch (MalformedURLException me){

      System.out.println("Converting process error");

 }

I hope this will help you.

My docker container has no internet

I've had a similar problem for the last few days. For me the cause was a combination of systemd, docker and my hosting provider. I'm running up-to-date CentOS (7.7.1908).

My hosting provider automatically generates a config file for systemd-networkd. Starting with systemd 219 which is the current version for CentOS 7, systemd-networkd took control of network-related sysctl parameters. Docker seems to be incompatible with this version and will reset the IP-Forwarding flags everytime a container is launched.

My solution was to add IPForward=true in the [Network]-section of my provider-generated config file. This file might be in several places, most likely in /etc/systemd/network.

The process is also described in the official docker docs: https://docs.docker.com/v17.09/engine/installation/linux/linux-postinstall/#ip-forwarding-problems

Create a .csv file with values from a Python list

Jupyter notebook

Let's say that your list name is A

Then you can code the following and you will have it as a csv file (columns only!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()

jQuery Ajax error handling, show custom exception messages

jQuery.parseJSON is useful for success and error.

$.ajax({
    url: "controller/action",
    type: 'POST',
    success: function (data, textStatus, jqXHR) {
        var obj = jQuery.parseJSON(jqXHR.responseText);
        notify(data.toString());
        notify(textStatus.toString());
    },
    error: function (data, textStatus, jqXHR) { notify(textStatus); }
});

How can I convert a Unix timestamp to DateTime and vice versa?

System.DateTimeOffset.Now.ToUnixTimeSeconds()

ModuleNotFoundError: What does it mean __main__ is not a package?

Simply remove the dot for the relative import and do:

from p_02_paying_debt_off_in_a_year import compute_balance_after

How to select the first row for each group in MySQL?

I have not seen the following solution among the answers, so I thought I'd put it out there.

The problem is to select rows which are the first rows when ordered by AnotherColumn in all groups grouped by SomeColumn.

The following solution will do this in MySQL. id has to be a unique column which must not hold values containing - (which I use as a separator).

select t1.*
from mytable t1
inner join (
  select SUBSTRING_INDEX(
    GROUP_CONCAT(t3.id ORDER BY t3.AnotherColumn DESC SEPARATOR '-'),
    '-', 
    1
  ) as id
  from mytable t3
  group by t3.SomeColumn
) t2 on t2.id = t1.id


-- Where 
SUBSTRING_INDEX(GROUP_CONCAT(id order by AnotherColumn desc separator '-'), '-', 1)
-- can be seen as:
FIRST(id order by AnotherColumn desc)

-- For completeness sake:
SUBSTRING_INDEX(GROUP_CONCAT(id order by AnotherColumn desc separator '-'), '-', -1)
-- would then be seen as:
LAST(id order by AnotherColumn desc)

There is a feature request for FIRST() and LAST() in the MySQL bug tracker, but it was closed many years back.

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

Gson: Directly convert String to JsonObject (no POJO)

The JsonParser constructor has been deprecated. Use the static method instead:

JsonObject asJsonObject = JsonParser.parseString(request.schema).getAsJsonObject();

How do I exit the Vim editor?

Vim has three modes of operation: Input mode, Command mode & Ex mode.

Input mode - everything that you type, all keystrokes are echoed on the screen.

Command mode or Escape mode - everything that you type in this mode is interpreted as a command.

Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.

In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.

Exiting from ex mode

  1. You need to be sure that you are in the Command mode. To do that, simply press the Esc key.

  2. Go to the ex mode by pressing the : key

  3. Use any of the following combinations in ex mode to exit:

    :q - quit :q! - quit without saving :wq - save & quit or write & quit :wq! - same as wq, but force write in case file permissions are readonly :x - write & quit :qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt

Exiting from command mode

  1. Press the escape key. You probably have done this already if you are in command mode.

  2. Press capital ZZ (shift zz) - save & exit

  3. Press capital ZQ (shift zq) - exit without saving.

What is the role of "Flatten" in Keras?

If you read the Keras documentation entry for Dense, you will see that this call:

Dense(16, input_shape=(5,3))

would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')

EDIT: As some people struggled to understand - here you have an explaining image:

enter image description here

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

How to join on multiple columns in Pyspark?

You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

df1 = sqlContext.createDataFrame(
    [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
    ("x1", "x2", "x3"))

df2 = sqlContext.createDataFrame(
    [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))

df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()

## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## |  2|  b|3.0|  2|  b|0.0|
## +---+---+---+---+---+---+

How to copy text from a div to clipboard

Adding the link as an Answer to draw more attention to Aaron Lavers' comment below the first answer.

This works like a charm - http://clipboardjs.com. Just add the clipboard.js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.

jquery select option click handler

_x000D_
_x000D_
$('#mySelect').on('change', function() {_x000D_
  var value = $(this).val();_x000D_
  alert(value);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>_x000D_
<select id="mySelect">_x000D_
  <option value='1'>1</option>_x000D_
  <option value='2'>2</option>_x000D_
  <option value='3'>3</option>_x000D_
  <option value='4'>4</option>_x000D_
  <option value='5'>5</option>_x000D_
  <option value='6'>6</option>_x000D_
  <option value='7'>7</option>_x000D_
  <option value='8'>8</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


EXAMPLE

Convert Python program to C/C++ code?

If the C variant needs x hours less, then I'd invest that time in letting the algorithms run longer/again

"invest" isn't the right word here.

  1. Build a working implementation in Python. You'll finish this long before you'd finish a C version.

  2. Measure performance with the Python profiler. Fix any problems you find. Change data structures and algorithms as necessary to really do this properly. You'll finish this long before you finish the first version in C.

  3. If it's still too slow, manually translate the well-designed and carefully constructed Python into C.

    Because of the way hindsight works, doing the second version from existing Python (with existing unit tests, and with existing profiling data) will still be faster than trying to do the C code from scratch.

This quote is important.

Thompson's Rule for First-Time Telescope Makers
It is faster to make a four-inch mirror and then a six-inch mirror than to make a six-inch mirror.

Bill McKeenan
Wang Institute

How to use class from other files in C# with visual studio?

namespace TestCSharp2
{
    **public** class Class2
    {
        int i;
        public void setValue(int i)
        {
            this.i = i;
        }
        public int getValue()
        {
        return this.i;
        }
    }
}

Add the 'Public' declaration before 'class Class2'.

TypeError: 'float' object not iterable

use

range(count)

int and float are not iterable

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How to send a PUT/DELETE request in jQuery?

From here, you can do this:

/* Extend jQuery with functions for PUT and DELETE requests. */

function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}

jQuery.extend({
    put: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'PUT');
    },
    delete_: function(url, data, callback, type) {
        return _ajax_request(url, data, callback, type, 'DELETE');
    }
});

It's basically just a copy of $.post() with the method parameter adapted.

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

How to format numbers by prepending 0 to single-digit numbers?

Quick and dirty one liner....

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}

How can I find the last element in a List<>?

Why not just use the Count property on the List?

for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)

Docker: Container keeps on restarting again on again

try running

docker stop CONTAINER_ID & docker rm -v CONTAINER_ID

Thanks

Check if a user has scrolled to the bottom

To stop repeated alert of Nick's answer

ScrollActivate();

function ScrollActivate() {
    $(window).on("scroll", function () {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            $(window).off("scroll");
            alert("near bottom!");
        }
    });
}

Azure SQL Database "DTU percentage" metric

A DTU is a unit of measure for the performance of a service tier and is a summary of several database characteristics. Each service tier has a certain number of DTUs assigned to it as an easy way to compare the performance level of one tier versus another.

Database Throughput Unit (DTU): DTUs provide a way to describe the relative capacity of a performance level of Basic, Standard, and Premium databases. DTUs are based on a blended measure of CPU, memory, reads, and writes. As DTUs increase, the power offered by the performance level increases. For example, a performance level with 5 DTUs has five times more power than a performance level with 1 DTU. A maximum DTU quota applies to each server.

The DTU Quota applies to the server, not the individual databases and each server has a maximum of 1600 DTUs. The DTU% is the percentage of units your particular database is using and it seems that this number can go over 100% of the DTU rating of the service tier (I assume to the limit of the server). This percentage number is designed to help you choose the appropriate service tier.

From down toward the bottom of this announcement:

For example, if your DTU consumption shows a value of 80%, it indicates it is consuming DTU at the rate of 80% of the limit an S2 database would have. If you see values greater than 100% in this view it means that you need a performance tier larger than S2.

As an example, let’s say you see a percentage value of 300%. This tells you that you are using three times more resources than would be available in an S2. To determine a reasonable starting size, compare the DTUs available in an S2 (50 DTUs) with the next higher sizes (P1 = 100 DTUs, or 200% of S2, P2 = 200 DTUs or 400% of S2). Because you are at 300% of S2 you would want to start with a P2 and re-test.

How can I add "href" attribute to a link dynamically using JavaScript?

document.getElementById('link-id').href = "new-href";

I know this is an old post, but here's a one-liner that might be more suitable for some folks.

MySql difference between two timestamps in days?

If you're happy to ignore the time portion in the columns, DATEDIFF() will give you the difference you're looking for in days.

SELECT DATEDIFF('2010-10-08 18:23:13', '2010-09-21 21:40:36') AS days;
+------+
| days |
+------+
|   17 |
+------+

Convert .cer certificate to .jks

keytool comes with the JDK installation (in the bin folder):

keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"

This will create a new keystore and add just your certificate to it.

So, you can't convert a certificate to a keystore: you add a certificate to a keystore.

How can I get the name of an html page in Javascript?

Current page: It's possible to do even shorter. This single line sound more elegant to find the current page's file name:

var fileName = location.href.split("/").slice(-1); 

or...

var fileName = location.pathname.split("/").slice(-1)

This is cool to customize nav box's link, so the link toward the current is enlighten by a CSS class.

JS:

$('.menu a').each(function() {
    if ($(this).attr('href') == location.href.split("/").slice(-1)){ $(this).addClass('curent_page'); }
});

CSS:

a.current_page { font-size: 2em; color: red; }

How to extract duration time from ffmpeg output?

Best Solution: cut the export do get something like 00:05:03.22

ffmpeg -i input 2>&1 | grep Duration | cut -c 13-23

Remove characters from a string

ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')

Correct way to delete cookies server-side

For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

And use it the common way to set cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

and to delete the cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

Top 1 with a left join

Use OUTER APPLY instead of LEFT JOIN:

SELECT u.id, mbg.marker_value 
FROM dps_user u
OUTER APPLY 
    (SELECT TOP 1 m.marker_value, um.profile_id
     FROM dps_usr_markers um (NOLOCK)
         INNER JOIN dps_markers m (NOLOCK) 
             ON m.marker_id= um.marker_id AND 
                m.marker_key = 'moneyBackGuaranteeLength'
     WHERE um.profile_id=u.id 
     ORDER BY m.creation_date
    ) AS MBG
WHERE u.id = 'u162231993';

Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

How to read GET data from a URL using JavaScript?

I also made a fairly simple function. You call on it by: get("yourgetname");

and get whatever there was. (now that i wrote it i noticed it will give you %26 if you had a & in your value..)

function get(name){
  var url = window.location.search;
  var num = url.search(name);
  var namel = name.length;
  var frontlength = namel+num+1; //length of everything before the value 
  var front = url.substring(0, frontlength);  
  url = url.replace(front, "");  
  num = url.search("&");

 if(num>=0) return url.substr(0,num); 
 if(num<0)  return url;             
}

Turn a string into a valid filename?

Though you have to be careful. It is not clearly said in your intro, if you are looking only at latine language. Some words can become meaningless or another meaning if you sanitize them with ascii characters only.

imagine you have "forêt poésie" (forest poetry), your sanitization might give "fort-posie" (strong + something meaningless)

Worse if you have to deal with chinese characters.

"???" your system might end up doing "---" which is doomed to fail after a while and not very helpful. So if you deal with only files I would encourage to either call them a generic chain that you control or to keep the characters as it is. For URIs, about the same.

Execution failed for task ':app:compileDebugAidl': aidl is missing

I had the same error i fixed it by going to the build.gradle (Module: app) and changed this line from :

 buildToolsVersion "23.0.0 rc1"

to :

buildToolsVersion "22.0.1"

You will need to go the SDK Manager and check if you have the 22.0.1 build tools. If not, you can use the right build tools but avoid the 23.0.0 rc1.

How to create a custom navigation drawer in android

Android Navigation Drawer using Activity I just followed the example :http://antonioleiva.com/navigation-view/

You just need few Customization:

public class MainActivity extends AppCompatActivity  {

public static final String AVATAR_URL = "http://lorempixel.com/200/200/people/1/";


private DrawerLayout drawerLayout;
private View content;
private Toolbar toolbar;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    initToolbar();
    setupDrawerLayout();

    content = findViewById(R.id.content);
    drawerToggle = setupDrawerToggle();
    final ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.avatar);
    Picasso.with(this).load(AVATAR_URL).transform(new CircleTransform()).into(avatar);


}


private void initToolbar() {
    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}
private ActionBarDrawerToggle setupDrawerToggle() {
    return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,  R.string.drawer_close);
}

   @Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    drawerToggle.onConfigurationChanged(newConfig);
}
 private void setupDrawerLayout() {

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            int id = menuItem.getItemId();

          switch (id) {
                case R.id.drawer_home:
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);
                    finish();
                    break;
                case R.id.drawer_favorite:
                    Intent j = new Intent(getApplicationContext(), SecondActivity.class);
                    startActivity(j);
                    finish();
                    break;

            }


        return true;
    }
});

} Here is the xml Layout

<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap" />

    </android.support.design.widget.AppBarLayout>



</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/drawer"/>

Add drawer.xml in menu

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<group
    android:checkableBehavior="single">

    <item
        android:id="@+id/drawer_home"
        android:checked="true"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/home"/>

    <item
        android:id="@+id/drawer_favourite"
        android:icon="@drawable/ic_favorite_black_24dp"
        android:title="@string/favourite"/>
    ...

    <item
        android:id="@+id/drawer_settings"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="@string/settings"/>

</group>

To open and close drawer add this values in string.xml

<string name="drawer_open">Open</string>
<string name="drawer_close">Close</string>

drawer.xml

enter code here

<ImageView
    android:id="@+id/avatar"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_margin="@dimen/spacing_large"
    android:elevation="4dp"
    tools:src="@drawable/ic_launcher"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/email"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:text="Username"
    android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>
<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="@dimen/spacing_large"
    android:layout_marginStart="@dimen/spacing_large"
    android:layout_marginBottom="@dimen/spacing_large"
    android:text="[email protected]"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

How to initialize private static members in C++?

Also working in privateStatic.cpp file :

#include <iostream>

using namespace std;

class A
{
private:
  static int v;
};

int A::v = 10; // possible initializing

int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}

// g++ privateStatic.cpp -o privateStatic && ./privateStatic

Determine if string is in list in JavaScript

RegExp is universal, but I understand that you're working with arrays. So, check out this approach. I use to use it, and it's very effective and blazing fast!

var str = 'some string with a';
var list = ['a', 'b', 'c'];
var rx = new RegExp(list.join('|'));

rx.test(str);

You can also apply some modifications, i.e.:

One-liner

new RegExp(list.join('|')).test(str);

Case insensitive

var rx = new RegExp(list.join('|').concat('/i'));


And many others!

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

Best way to list files in Java, sorted by Date Modified?

If the files you are sorting can be modified or updated at the same time the sort is being performed:


Java 8+

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .collect(Collectors.toMap(Function.identity(), File::lastModified))
            .entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue())
//            .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))  // replace the previous line with this line if you would prefer files listed newest first
            .map(Map.Entry::getKey)
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Java 7

private static List<File> listFilesOldestFirst(final String directoryPath) throws IOException {
    final List<File> files = Arrays.asList(new File(directoryPath).listFiles());
    final Map<File, Long> constantLastModifiedTimes = new HashMap<File,Long>();
    for (final File f : files) {
        constantLastModifiedTimes.put(f, f.lastModified());
    }
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(final File f1, final File f2) {
            return constantLastModifiedTimes.get(f1).compareTo(constantLastModifiedTimes.get(f2));
        }
    });
    return files;
}


Both of these solutions create a temporary map data structure to save off a constant last modified time for each file in the directory. The reason we need to do this is that if your files are being updated or modified while your sort is being performed then your comparator will be violating the transitivity requirement of the comparator interface's general contract because the last modified times may be changing during the comparison.

If, on the other hand, you know the files will not be updated or modified during your sort, you can get away with pretty much any other answer submitted to this question, of which I'm partial to:

Java 8+ (No concurrent modifications during sort)

private static List<Path> listFilesOldestFirst(final String directoryPath) throws IOException {
    try (final Stream<Path> fileStream = Files.list(Paths.get(directoryPath))) {
        return fileStream
            .map(Path::toFile)
            .sorted(Comparator.comparing(File::lastModified))
            .map(File::toPath)  // remove this line if you would rather work with a List<File> instead of List<Path>
            .collect(Collectors.toList());
    }
}

Note: I know you can avoid the translation to and from File objects in the above example by using Files::getLastModifiedTime api in the sorted stream operation, however, then you need to deal with checked IO exceptions inside your lambda which is always a pain. I'd say if performance is critical enough that the translation is unacceptable then I'd either deal with the checked IOException in the lambda by propagating it as an UncheckedIOException or I'd forego the Files api altogether and deal only with File objects:

final List<File> sorted = Arrays.asList(new File(directoryPathString).listFiles());
sorted.sort(Comparator.comparing(File::lastModified));

What good technology podcasts are out there?

I am going out on a limb here to say that, don't get caught up in too many podcasts or blogs, but rather dive into technology/code and good tech books.

although +1 to;

  • Thoughtworks - IT matters
  • Software Engineering Radio
  • Pragmatic podcasts
  • Alt.Net podcasts
  • Hanselminutes

and while not strictly technology

  • Enterprise Thought Leaders from Stanford University, which often has speakers from fortune 500 and tech startups on how they made it.

Insertion Sort vs. Selection Sort

Although Time Complexity of selection sort and insertion sort is the same, that is n(n - 1)/2. The average performance insertion sort is better. Tested on my i5 cpu with random 30000 integers, selection sort took 1.5s in average, while insertion sort take 0.6s in average.

The "backspace" escape character '\b': unexpected behavior?

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

How to add an element to the beginning of an OrderedDict?

If you know you will want a 'c' key, but do not know the value, insert 'c' with a dummy value when you create the dict.

d1 = OrderedDict([('c', None), ('a', '1'), ('b', '2')])

and change the value later.

d1['c'] = 3

git clone from another directory

It is worth mentioning that the command works similarly on Linux:

git clone path/to/source/folder path/to/destination/folder

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
    var model = await response.Content.ReadAsAsync<List<Job>>();

How to get IP address of the device from code?

public static String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return null;
}

I've added inetAddress instanceof Inet4Address to check if it is a ipv4 address.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

What is the main difference between Inheritance and Polymorphism?

Polymorphism: Suppose you work for a company that sells pens. So you make a very nice class called "Pen" that handles everything that you need to know about a pen. You write all sorts of classes for billing, shipping, creating invoices, all using the Pen class. A day boss comes and says, "Great news! The company is growing and we are selling Books & CD's now!" Not great news because now you have to change every class that uses Pen to also use Book & CD. But what if you had originally created an interface called "SellableProduct", and Pen implemented this interface. Then you could have written all your shipping, invoicing, etc classes to use that interface instead of Pen. Now all you would have to do is create a new class called Book & CompactDisc which implements the SellableProduct interface. Because of polymorphism, all of the other classes could continue to work without change! Make Sense?

So, it means using Inheritance which is one of the way to achieve polymorphism.

Polymorhism can be possible in a class / interface but Inheritance always between 2 OR more classes / interfaces. Inheritance always conform "is-a" relationship whereas it is not always with Polymorphism (which can conform both "is-a" / "has-a" relationship.

throwing an exception in objective-c/cocoa

Sample code for case: @throw([NSException exceptionWithName:...

- (void)parseError:(NSError *)error
       completionBlock:(void (^)(NSString *error))completionBlock {


    NSString *resultString = [NSString new];

    @try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    resultString = dictFromData[@"someKey"];
    ...


} @catch (NSException *exception) {

      NSLog( @"Caught Exception Name: %@", exception.name);
      NSLog( @"Caught Exception Reason: %@", exception.reason );

    resultString = exception.reason;

} @finally {

    completionBlock(resultString);
}

}

Using:

[self parseError:error completionBlock:^(NSString *error) {
            NSLog(@"%@", error);
        }];

Another more advanced use-case:

- (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {

NSString *resultString = [NSString new];

NSException* customNilException = [NSException exceptionWithName:@"NilException"
                                                          reason:@"object is nil"
                                                        userInfo:nil];

NSException* customNotNumberException = [NSException exceptionWithName:@"NotNumberException"
                                                                reason:@"object is not a NSNumber"
                                                              userInfo:nil];

@try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    NSArray * array = dictFromData[@"someArrayKey"];

    for (NSInteger i=0; i < array.count; i++) {

        id resultString = array[i];

        if (![resultString isKindOfClass:NSNumber.class]) {

            [customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;

            break;

        } else if (!resultString){

            @throw customNilException;        // <======

            break;
        }

    }

} @catch (SomeCustomException * sce) {
    // most specific type
    // handle exception ce
    //...
} @catch (CustomException * ce) {
    // most specific type
    // handle exception ce
    //...
} @catch (NSException *exception) {
    // less specific type

    // do whatever recovery is necessary at his level
    //...
    // rethrow the exception so it's handled at a higher level

    @throw (SomeCustomException * customException);

} @finally {
    // perform tasks necessary whether exception occurred or not

}

}

Sorting a Python list by two fields

like this:

import operator
list1 = sorted(csv1, key=operator.itemgetter(1, 2))

Selenium Webdriver submit() vs click()

There is a difference between click() and submit().

submit() submits the form and executes the url that is given by the "action" attribute. If you have any javascript-function or jquery-plugin running to submit the form e.g. via ajax, submit() will ignore it. With click() the javascript-functions will be executed.

Android: ProgressDialog.show() crashes with getApplicationContext

For using dialogs inside activities, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     mContext = this;

     //using mContext here refering to activity context
     mBuilder = new AlertDialog.Builder(mContext);
     //...
     //rest of the code
     //...
}

For using dialogs inside fragments, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View mRootView = inflater.inflate(R.layout.fragment_layout, container, false);
      mContext = getActivity();

      //using mContext here refering to fragment's hosting activity context
      mBuilder = new AlertDialog.Builder(mContext);
      //...
      //rest of the code
      //...
      return mRootView;
}

That's it ^_^

Internal Error 500 Apache, but nothing in the logs?

In my case it was the ErrorLog directive in httpd.conf. Just accidently noticed it already after I gave up. Decided to share the discovery ) Now I know where to find the 500-errors.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How can I mock the JavaScript window object using Jest?

We can also define it using global in setupTests

// setupTests.js
global.open = jest.fn()

And call it using global in the actual test:

// yourtest.test.js
it('correct url is called', () => {
    statementService.openStatementsReport(111);
    expect(global.open).toBeCalled();
});

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

LocalDate to java.util.Date and vice versa simplest conversion?

tl;dr

Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this

Nope. You did it properly, and as concisely as possible.

java.util.Date.from(                     // Convert from modern java.time class to troublesome old legacy class.  DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
    myLocalDate                          // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC. 
    .atStartOfDay(                       // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
        ZoneId.of( "America/Montreal" )  // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”. 
    )                                    // Produce a `ZonedDateTime` object. 
    .toInstant()                         // Extract an `Instant` object, a moment always in UTC.
)

Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.

So in converting a date-only (LocalDate) to a date-time we must apply a time zone (ZoneId) to get a zoned value (ZonedDateTime), and then move into UTC (Instant) to match the definition of a java.util.Date.

Details

Firstly, avoid the old legacy date-time classes such as java.util.Date whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.

But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.

Table of all date-time types in Java, both modern and legacy

java.util.Date ? java.time.LocalDate

Keep in mind that a java.util.Date is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate class represents a date-only value without time-of-day and without time zone.

Going from java.util.Date to java.time means converting to the equivalent class of java.time.Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

So we need to move that Instant into a time zone. We apply ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

From there, ask for a date-only, a LocalDate.

LocalDate ld = zdt.toLocalDate();

java.time.LocalDate ? java.util.Date

To move the other direction, from a java.time.LocalDate to a java.util.Date means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00. Let java.time determine that value by calling atStartOfDay on the LocalDate.

ZonedDateTime zdt = myLocalDate.atStartOfDay( z );

Now extract an Instant.

Instant instant = zdt.toInstant();

Convert that Instant to java.util.Date by calling from( Instant ).

java.util.Date d = java.util.Date.from( instant );

More info


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Best practice: PHP Magic Methods __set and __get

You only need to use magic if the object is indeed "magical". If you have a classic object with fixed properties then use setters and getters, they work fine.

If your object have dynamic properties for example it is part of a database abstraction layer, and its parameters are set at runtime then you indeed need the magic methods for convenience.

Format in kotlin string templates

Since String.format is only an extension function (see here) which internally calls java.lang.String.format you could write your own extension function using Java's DecimalFormat if you need more flexibility:

fun Double.format(fracDigits: Int): String {
    val df = DecimalFormat()
    df.setMaximumFractionDigits(fracDigits)
    return df.format(this)
}

println(3.14159.format(2)) // 3.14

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

How to get numeric position of alphabets in java?

First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.

For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.

How to use confirm using sweet alert?

document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};

Read CSV with Scanner()

Scanner.next() does not read a newline but reads the next token, delimited by whitespace (by default, if useDelimiter() was not used to change the delimiter pattern). To read a line use Scanner.nextLine().

Once you read a single line you can use String.split(",") to separate the line into fields. This enables identification of lines that do not consist of the required number of fields. Using useDelimiter(","); would ignore the line-based structure of the file (each line consists of a list of fields separated by a comma). For example:

while (inputStream.hasNextLine())
{
    String line = inputStream.nextLine();
    String[] fields = line.split(",");
    if (fields.length >= 4) // At least one address specified.
    {
        for (String field: fields) System.out.print(field + "|");
        System.out.println();
    }
    else
    {
        System.err.println("Invalid record: " + line);
    }
}

As already mentioned, using a CSV library is recommended. For one, this (and useDelimiter(",") solution) will not correctly handle quoted identifiers containing , characters.

How to retrieve field names from temporary table (SQL Server 2008)

Anthony

try the below one. it will give ur expected output

select c.name as Fields from 
tempdb.sys.columns c
    inner join tempdb.sys.tables t
 ON c.object_id = t.object_id
where t.name like '#MyTempTable%'

Get width height of remote image from url

ES6: Using async/await you can do below getMeta function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await keyword and change variable end to img, and change var to let keyword). You need to run getMeta by await only from async function (run).

_x000D_
_x000D_
function getMeta(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject();
        img.src = url;
    });
}

async function run() {

  let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");

  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}

run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_

Find file in directory from command line

I use this script to quickly find files across directories in a project. I have found it works great and takes advantage of Vim's autocomplete by opening up and closing an new buffer for the search. It also smartly completes as much as possible for you so you can usually just type a character or two and open the file across any directory in your project. I started using it specifically because of a Java project and it has saved me a lot of time. You just build the cache once when you start your editing session by typing :FC (directory names). You can also just use . to get the current directory and all subdirectories. After that you just type :FF (or FS to open up a new split) and it will open up a new buffer to select the file you want. After you select the file the temp buffer closes and you are inside the requested file and can start editing. In addition, here is another link on Stack Overflow that may help.

Google Maps v2 - set both my location and zoom in

@CommonsWare's answer doesn't not actually work. I found that this is working properly :

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));

What is the difference between <section> and <div>?

Take caution not to overuse the section tag as a replacement for a div element. A section tag should define a significant region within the context of the body. Semantically, HTML5 encourages us to define our document as follows:

_x000D_
_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
    <header></header>_x000D_
    <section>_x000D_
        <h1></h1>_x000D_
        <div>_x000D_
            <span></span>_x000D_
        </div>_x000D_
        <div></div>_x000D_
    </section>_x000D_
    <footer></footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This strategy allows web robots and automated screen readers to better understand the flow of your content. This markup clearly defines where your major page content is contained. Of course, headers and footers are often common across hundreds if not thousands of pages within a website. The section tag should be limited to explain where the unique content is contained. Within the section tag, we should then continue to markup and control the content with HTML tags which are lower in the hierarchy, like h1, div, span, etc.

In most simple pages, there should only be a single section tag, not multiple ones. Please also consider also that there are other interesting HTML5 tags which are similar to section. Consider using article, summary, aside and others within your document flow. As you can see, these tags further enhance our ability to define the major regions of the HTML document.

How do I create executable Java program?

On the command line, navigate to the root directory of the Java files you wish to make executable.

Use this command:

jar -cvf [name of jar file] [name of directory with Java files]

This will create a directory called META-INF in the jar archive. In this META-INF there is a file called MANIFEST.MF, open this file in a text editor and add the following line:

Main-Class: [fully qualified name of your main class]

then use this command:

java -jar [name of jar file]

and your program will run :)

How to confirm RedHat Enterprise Linux version?

That is the release version of RHEL, or at least the release of RHEL from which the package supplying /etc/redhat-release was installed. A file like that is probably the closest you can come; you could also look at /etc/lsb-release.

It is theoretically possible to have packages installed from a mix of versions (e.g. upgrading part of the system to 5.5 while leaving other parts at 5.4), so if you depend on the versions of specific components you will need to check for those individually.

How to undo a git merge with conflicts

Assuming you are using the latest git,

git merge --abort

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I had the same issue and was able to resolve it by manually removing the MapFragment in the onDestroy() method of the Fragment class. Here is code that works and references the MapFragment by ID in the XML:

@Override
public void onDestroyView() {
    super.onDestroyView();
    MapFragment f = (MapFragment) getFragmentManager()
                                         .findFragmentById(R.id.map);
    if (f != null) 
        getFragmentManager().beginTransaction().remove(f).commit();
}

If you don't remove the MapFragment manually, it will hang around so that it doesn't cost a lot of resources to recreate/show the map view again. It seems that keeping the underlying MapView is great for switching back and forth between tabs, but when used in fragments this behavior causes a duplicate MapView to be created upon each new MapFragment with the same ID. The solution is to manually remove the MapFragment and thus recreate the underlying map each time the fragment is inflated.

I also noted this in another answer [1].

Encode/Decode URLs in C++

Answering my own question...

libcurl has curl_easy_escape for encoding.

For decoding, curl_easy_unescape

Combining paste() and expression() functions in plot labels

Use substitute instead.

labNames <- c('xLab','yLab')
plot(c(1:10),
     xlab=substitute(paste(nn, x^2), list(nn=labNames[1])),
     ylab=substitute(paste(nn, y^2), list(nn=labNames[2])))

How do I return JSON without using a template in Django?

In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.

However, you can have HTML that is rendered from a template withing your JSON response.

html = render_to_string("some.html", some_dictionary)
serialized_data = simplejson.dumps({"html": html})
return HttpResponse(serialized_data, mimetype="application/json")

How to close the command line window after running a batch file?

It should close automatically, if it doesn't it means that it is stuck on the first command.

In your example it should close either automatically (without the exit) or explicitly with the exit. I think the issue is with the first command you are running not returning properly.

As a work around you can try using

start "" tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B

How can I close a login form and show the main form without my application closing?

you should do it the other way round:

Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform

EDIT: As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.

How to hide Table Row Overflow?

Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53

Just define width of the table and width for each table cell

something like

table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}

It works like a charm :o)

What is python's site-packages directory?

site-packages is the target directory of manually built Python packages. When you build and install Python packages from source (using distutils, probably by executing python setup.py install), you will find the installed modules in site-packages by default.

There are standard locations:

  • Unix (pure)1: prefix/lib/pythonX.Y/site-packages
  • Unix (non-pure): exec-prefix/lib/pythonX.Y/site-packages
  • Windows: prefix\Lib\site-packages

1 Pure means that the module uses only Python code. Non-pure can contain C/C++ code as well.

site-packages is by default part of the Python search path, so modules installed there can be imported easily afterwards.


Useful reading

How to percent-encode URL parameters in Python?

Python 2

From the docs:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

By the way have a look at urlencode

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

How to get a list of all files in Cloud Storage in a Firebase app?

To do this with JS

You can append them directly to your div container, or you can push them to an array. The below shows you how to append them to your div.

1) When you store your images in storage create a reference to the image in your firebase database with the following structure

/images/(imageName){
   description: "" , 
   imageSrc : (imageSource) 
}

2) When you load you document pull all your image source URLs from the database rather than the storage with the following code

$(document).ready(function(){

var query = firebase.database().ref('images/').orderByKey();
query.once("value").then(function(snapshot){

    snapshot.forEach(function(childSnapshot){

        var imageName = childSnapshot.key;
        var childData = childSnapshot.val();
        var imageSource = childData.url;

        $('#imageGallery').append("<div><img src='"+imageSource+"'/></div>");

    })
})
});

How to Decrease Image Brightness in CSS

OP wants to decrease brightness, not increase it. Opacity makes the image look brighter, not darker.

You can do this by overlaying a black div over the image and setting the opacity of that div.

<style>
#container {
    position: relative;
}
div.overlay {
    opacity: .9;
    background-color: black;
    position: absolute;
    left: 0; top: 0; height: 256px; width: 256px;
}
</style>

Normal:<br />
<img src="http://i.imgur.com/G8eyr.png">
<br />
Decreased brightness:<br />
<div id="container">
    <div class="overlay"></div>
    <img src="http://i.imgur.com/G8eyr.png">
</div>

DEMO

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

Can you use Microsoft Entity Framework with Oracle?

In case you don't know it already, Oracle has released ODP.NET which supports Entity Framework. It doesn't support code first yet though.

http://www.oracle.com/technetwork/topics/dotnet/index-085163.html

Finding Variable Type in JavaScript

To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):

In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)

The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.

As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

Custom exception type

ES6

With the new class and extend keywords it’s now much easier:

class CustomError extends Error {
  constructor(message) {
    super(message);
    //something
  }
}

Re-assign host access permission to MySQL user

I haven't had to do this, so take this with a grain of salt and a big helping of "test, test, test".

What happens if (in a safe controlled test environment) you directly modify the Host column in the mysql.user and probably mysql.db tables? (E.g., with an update statement.) I don't think MySQL uses the user's host as part of the password encoding (the PASSWORD function doesn't suggest it does), but you'll have to try it to be sure. You may need to issue a FLUSH PRIVILEGES command (or stop and restart the server).

For some storage engines (MyISAM, for instance), you may also need to check/modify the .frm file any views that user has created. The .frm file stores the definer, including the definer's host. (I have had to do this, when moving databases between hosts where there had been a misconfiguration causing the wrong host to be recorded...)

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

How do I work with a git repository within another repository?

Consider using subtree instead of submodules, it will make your repo users life much easier. You may find more detailed guide in Pro Git book.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.

robocopy - cmd copy utility

/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans

Create en empty dir like this:

mkdir empty

overwrite broken folder with empty like this:

robocopy /copyall /mir /b empty broken

and then delete that folder

rd broken /s
rd empty /s

If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

Bash integer comparison

I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;
esac

When to use setAttribute vs .attribute= in JavaScript?

One case I found where setAttribute is necessary is when changing ARIA attributes, since there are no corresponding properties. For example

x.setAttribute('aria-label', 'Test');
x.getAttribute('aria-label');

There's no x.arialabel or anything like that, so you have to use setAttribute.

Edit: x["aria-label"] does not work. You really do need setAttribute.

x.getAttribute('aria-label')
null
x["aria-label"] = "Test"
"Test"
x.getAttribute('aria-label')
null
x.setAttribute('aria-label', 'Test2')
undefined
x["aria-label"]
"Test"
x.getAttribute('aria-label')
"Test2"

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Git - How to use .netrc file on Windows to save user and password

This will let Git authenticate on HTTPS using .netrc:

  • The file should be named _netrc and located in c:\Users\<username>.
  • You will need to set an environment variable called HOME=%USERPROFILE% (set system-wide environment variables using the System option in the control panel. Depending on the version of Windows, you may need to select "Advanced Options".).
  • The password stored in the _netrc file cannot contain spaces (quoting the password will not work).

Submit HTML form on self page

You can leave action attribute blank. The form will automatically submit itself in the same page.

<form action="">

According to the w3c specification, action attribute must be non-empty valid url in general. There is also an explanation for some situations in which the action attribute may be left empty.

The action of an element is the value of the element’s formaction attribute, if the element is a Submit Button and has such an attribute, or the value of its form owner’s action attribute, if it has one, or else the empty string.

So they both still valid and works:

<form action="">
<form action="FULL_URL_STRING_OF_CURRENT_PAGE">

If you are sure your audience is using html5 browsers, you can even omit the action attribute:

<form>

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

SQL Select between dates

One more way to select between dates in SQLite is to use the powerful strftime function:

SELECT * FROM test WHERE strftime('%Y-%m-%d', date) BETWEEN "11-01-2011" AND "11-08-2011"

These are equivalent according to https://sqlite.org/lang_datefunc.html:

date(...)

strftime('%Y-%m-%d', ...)

but if you want more choice, you have it.

Using curl to upload POST data with files

You need to use the -F option:
-F/--form <name=content> Specify HTTP multipart POST data (H)

Try this:

curl \
  -F "userid=1" \
  -F "filecomment=This is an image file" \
  -F "image=@/home/user1/Desktop/test.jpg" \
  localhost/uploader.php

How to name variables on the fly?

It seems to me that you might be better off with a list rather than using orca1, orca2, etc, ... then it would be orca[1], orca[2], ...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list()
orca[1] <- "Hi"
orca[2] <- 59

Otherwise, assign is just what you want.

Pretty-print a Map in Java

As a quick and dirty solution leveraging existing infrastructure, you can wrap your uglyPrintedMap into a java.util.HashMap, then use toString().

uglyPrintedMap.toString(); // ugly
System.out.println( uglyPrintedMap ); // prints in an ugly manner

new HashMap<Object, Object>(jobDataMap).toString(); // pretty
System.out.println( new HashMap<Object, Object>(uglyPrintedMap) ); // prints in a pretty manner

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Changing the browser zoom level

I could't find a way to change the actual browser zoom level, but you can get pretty close with CSS transform: scale(). Here is my solution based on JavaScript and jQuery:

<!-- Trigger -->
<ul id="zoom_triggers">
    <li><a id="zoom_in">zoom in</a></li>
    <li><a id="zoom_out">zoom out</a></li>
    <li><a id="zoom_reset">reset zoom</a></li>
</ul>

<script>
    jQuery(document).ready(function($)
    {
        // Set initial zoom level
        var zoom_level=100;

        // Click events
        $('#zoom_in').click(function() { zoom_page(10, $(this)) });
        $('#zoom_out').click(function() { zoom_page(-10, $(this)) });
        $('#zoom_reset').click(function() { zoom_page(0, $(this)) });

        // Zoom function
        function zoom_page(step, trigger)
        {
            // Zoom just to steps in or out
            if(zoom_level>=120 && step>0 || zoom_level<=80 && step<0) return;

            // Set / reset zoom
            if(step==0) zoom_level=100;
            else zoom_level=zoom_level+step;

            // Set page zoom via CSS
            $('body').css({
                transform: 'scale('+(zoom_level/100)+')', // set zoom
                transformOrigin: '50% 0' // set transform scale base
            });

            // Adjust page to zoom width
            if(zoom_level>100) $('body').css({ width: (zoom_level*1.2)+'%' });
            else $('body').css({ width: '100%' });

            // Activate / deaktivate trigger (use CSS to make them look different)
            if(zoom_level>=120 || zoom_level<=80) trigger.addClass('disabled');
            else trigger.parents('ul').find('.disabled').removeClass('disabled');
            if(zoom_level!=100) $('#zoom_reset').removeClass('disabled');
            else $('#zoom_reset').addClass('disabled');
        }
    });
</script>

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

How to disable text selection highlighting

Working

CSS:

-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-touch-callout: none;
-webkit-user-select: none;

This should work, but it won't work for the old browsers. There is a browser compatibility issue.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

What I did in my case was to update

"lib": [
      "es2020",
      "dom"
    ]

with

"lib": [
  "es2016",
  "dom"
]

in my tsconfig.json file

Java converting int to hex and back again

It's worth mentioning that Java 8 has the methods Integer.parseUnsignedInt and Long.parseUnsignedLong that does what you wanted, specifically:

Integer.parseUnsignedInt("ffff8000",16) == -32768

The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had approximately the same problem with Laravel 5.5 on ubuntu, finally i've found a solution here to switch between the versions of php used by apache :

  1. sudo a2dismod php5
  2. sudo a2enmod php7.1
  3. sudo service apache2 restart

and it works

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


Sending Multipart File as POST parameters with RestTemplate requests

I had this issue and found a much simpler solution than using a ByteArrayResource.

Simply do

public void loadInvoices(MultipartFile invoices, String channel) throws IOException {

    init();

    Resource invoicesResource = invoices.getResource();

    LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("file", invoicesResource);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    httpHeaders.set("channel", channel);

    HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders);

    String url = String.format("%s/rest/inbound/invoices/upload", baseUrl);

    restTemplate.postForEntity(url, httpEntity, JobData.class);
}

It works, and no messing around with the file system or byte arrays.

Can't find the 'libpq-fe.h header when trying to install pg gem

I fixed the same error by doing a Ruby reinstall via rvm:

rvm reinstall 1.9.3

How do I obtain crash-data from my Android application?

I made my own version here : http://androidblogger.blogspot.com/2009/12/how-to-improve-your-application-crash.html

It's basically the same thing, but I'm using a mail rather than a http connexion to send the report, and, more important, I added some informations like application version, OS version, Phone model, or avalaible memory to my report...

How can I use Html.Action?

Another case is http redirection. If your page redirects http requests to https, then may be your partial view tries to redirect by itself.

It causes same problem again. For this problem, you can reorganize your .net error pages or iis error pages configuration.

Just make sure you are redirecting requests to right error or not found page and make sure this error page contains non problematic partial. If your page supports only https, do not forward requests to error page without using https, if error page contains partial, this partials tries to redirect seperately from requested url, it causes problem.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

Running an outside program (executable) in Python?

Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.

So you might try:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

Checking if jquery is loaded using Javascript

CAUTION: Do not use jQuery to test your jQuery

When you are using any of the code provided by other users and if you want to display the message on your window and not on the alert or console.log, Then make sure you use javascript and not jquery.

Not everyone want to use alert or console.log

alert('jquery is working');
console.log('jquery is working');

The code below will fail to display the message
Because we are using jquery inside the else (how the hell the message displays on your screen if you do not have jquery)

if ('undefined' == typeof window.jQuery) {
    $('#selector').appendTo('jquery is NOT working');
} else {
    $('#selector').appendTo('jquery is working');
}

Use JavaScript instead

if ('undefined' == typeof window.jQuery) {
    document.getElementById('selector').innerHTML = "jquery is NOT working";
} else {
    document.getElementById('selector').innerHTML = "jquery is working";
}