Programs & Examples On #String table

How to initialize private static members in C++?

The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h

class foo
{
    private:
        static int i;
};

But the initialization should be in source file.
File: foo.cpp

int foo::i = 0;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the static int i must be done outside of any function.

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (e.g. int, bool, char). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
    private:
        static int const i = 42;
};

Add class to an element in Angular 4

you can try this without any java script you can do that just by using CSS

img:active,
img:focus,
img:hover{ 
border: 10px solid red !important
}

of if your case is to add any other css class by clicking you can use query selector like

<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >

in controller first search for any image with red border and remove it then by passing the image id add the border class to that image

$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}

Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Run the following on the command line :

$ mysql.server start

Difference between web reference and service reference?

Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).

TypeLoadException says 'no implementation', but it is implemented

Our problem solved with updating windows! Our web application is on .Net 4.7.1 and c# 7.0. As we tested in different windowses, we understood that the problem will be solved by updating windows. Indeed, the problem was seen in windows 10 (version 1703) and also in a windows server 2012(not updated in last year). After updating both of them, the problem was solved. In fact, the asp.net minor version(the third part of the clr.dll version in C:\Windows\Microsoft.NET\Framework64\v4.0.30319 ) was changed a bit after the update.

Best way to strip punctuation from a string

Not necessarily simpler, but a different way, if you are more familiar with the re family.

import re, string
s = "string. With. Punctuation?" # Sample string 
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

C# equivalent of C++ vector, with contiguous memory?

C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap

Is it possible to use if...else... statement in React render function?

Try going with Switch case or ternary operator

render(){
    return (
        <div>
            <Element1/>
            <Element2/>
            // updated code works here
            {(() => {
                        switch (this.props.hasImage) {
                            case (this.props.hasImage):
                                return <MyImage />;
                            default:
                                return (
                                   <OtherElement/>; 
                                );
                        }
                    })()}
        </div>
    )
}

This worked for me and should work for you else. Try Ternary Operator

How to print strings with line breaks in java

Do this way:-

String newline = System.getProperty("line.separator");

private static final String mText = "SHOP MA" + newline +
        + "----------------------------" + newline +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + newline +
        + "No  Item  Qty  Price  Amount" + newline +
        + "1 Bread 1 50.00  50.00" + newline +
        + "____________________________" + newline;

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

problem with <select> and :after with CSS in WebKit

To my experience it simply does not work, unless you are willing to wrap your <select> in some wrapper. But what you can do instead is to use background image SVG. E.g.

    .archive .options select.opt {
    -moz-appearance: none;
    -webkit-appearance: none;
    padding-right: 1.25EM;
    appearance: none;
    position: relative;
    background-color: transparent;
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' height='10px' width='15px'%3E%3Ctext x='0' y='10' fill='gray'%3E%E2%96%BE%3C/text%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-size: 1.5EM 1EM;
    background-position: right center;
    background-clip: border-box;
    -moz-background-clip: border-box;
    -webkit-background-clip: border-box;
}

    .archive .options select.opt::-ms-expand {
        display: none;
    }

Just be careful with proper URL-encoding because of IE. You must use charset=utf8 (not just utf8), don't use double-quotes (") to delimit SVG attribute values, use apostrophes (') instead to simplify your life. URL-encode s (%3E). In case you havee to print any non-ASCII characters you have to obtain their UTF-8 representation (e.g. BabelMap can help you with that) and then provide that representation in URL-encoded form - e.g. for ? (U+25BE BLACK DOWN-POINTING SMALL TRIANGLE) UTF-8 representation is \xE2\x96\xBE which is %E2%96%BE when URL-encoded.

PHP-FPM and Nginx: 502 Bad Gateway

If you met the problem after upgrading php-fpm like me, try this: open /etc/php5/fpm/pool.d/www.conf uncomment the following lines:

listen.owner = www-data
listen.group = www-data
listen.mode = 0666

then restart php-fpm.

MySQL LIKE IN()?

Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (
'val1',
'val2',
'val3'
)

In REGEXP this won't work

REGEXP '
val1$|
val2$|
val3$
'

It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

Wildcards in a Windows hosts file

Here is the total configuration for those trying to accomplish the goal (wildcards in dev environment ie, XAMPP -- this example assumes all sites pointing to same codebase)

hosts file (add an entry)

file: %SystemRoot%\system32\drivers\etc\hosts

127.0.0.1   example.local

httpd.conf configuration (enable vhosts)

file: \XAMPP\etc\httpd.conf

# Virtual hosts
Include etc\extra\httpd-vhosts.conf

httpd-vhosts.conf configuration

file: XAMPP\etc\extra\httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "\path_to_XAMPP\htdocs"
    ServerName example.local
    ServerAlias *.example.local
#    SetEnv APP_ENVIRONMENT development
#    ErrorLog "logs\example.local-error_log"
#    CustomLog "logs\example.local-access_log" common
</VirtualHost>

restart apache

create pac file:

save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)

function FindProxyForURL(url, host) {
  if (shExpMatch(host, "*example.local")) {
    return "PROXY example.local";
  }
  return "DIRECT";
}

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

When to use RDLC over RDL reports?

From my experience, if you need high performance (this does depend slightly on your client specs) on large reports, go with rdlc. Additionally, rdlc reports give you a very full range of control over your data, you may be able to save yourself wasted database trips, etc. by using client side reports. On the project I'm currently working on, a critical report requires about 2 minutes to render on the server side, and pretty much takes out whichever reporting server it hits for that time. Switching it to client side rendering, we see performance much closer to 20-40 seconds with no load on the report server and less bandwidth used because only the datasets are being downloaded.

Your mileage may vary, and I find rdlc's add development and maintenance complexity, especially when your report has been designed as a server side report.

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.

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Rename all files in a folder with a prefix in a single command

With rnm (you will need to install it):

rnm -ns 'Unix_/fn/' *

Or

rnm -rs '/^/Unix_/' *

P.S : I am the author of this tool.

How to customize listview using baseadapter

Create your own BaseAdapter class and use it as following.

 public class NotificationScreen extends Activity
{

@Override
protected void onCreate_Impl(Bundle savedInstanceState)
{
    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);

}

}

Make your own BaseAdapter class and its separate xml file.

public class NotiFicationListAdapter  extends BaseAdapter
{
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)
{
this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}



public int getCount() 
{
 return data.size();
}



public Object getItem(int position) 
{
 return position;
}



public long getItemId(int position) 
{
    return position;
}



public View getView(int position, View convertView, ViewGroup parent) 
{
View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;
}

  }

BaseAdapter xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

Change it accordingly and use.

How to directly move camera to current location in Google Maps Android API v2?

Just change moveCamera to animateCamera like below

Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))

Deserialize from string instead TextReader

If you have the XML stored inside a string variable you could use a StringReader:

var xml = @"<car/>";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
    var car = (Car)serializer.Deserialize(reader);
}

Where can I find a list of Mac virtual key codes?

In addition to the keycodes supplied in other answers, there are also "usage IDs" used for key remapping in the newer APIs introduced in macOS Sierra:

Technical Note TN2450

Remapping Keys in macOS 10.12 Sierra

Under macOS Sierra 10.12, the mechanism for key remapping was changed. This Technical Note is for developers of key remapping software so that they can update their software to support macOS Sierra 10.12. We present 2 solutions for implementing key remapping functionality for macOS 10.12 in this Technical Note.

https://developer.apple.com/library/archive/technotes/tn2450/_index.html

Keyboard a and A - 0x04
Keyboard b and B - 0x05
Keyboard c and C - 0x06
Keyboard d and D - 0x07
Keyboard e and E - 0x08
...

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

Receiving JSON data back from HTTP request

If you are referring to the System.Net.HttpClient in .NET 4.5, you can get the content returned by GetAsync using the HttpResponseMessage.Content property as an HttpContent-derived object. You can then read the contents to a string using the HttpContent.ReadAsStringAsync method or as a stream using the ReadAsStreamAsync method.

The HttpClient class documentation includes this example:

  HttpClient client = new HttpClient();
  HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
  response.EnsureSuccessStatusCode();
  string responseBody = await response.Content.ReadAsStringAsync();

Is it better to use NOT or <> when comparing values?

The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Waiting till the async task finish its work

Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.

You've got pretty much 2 options here;

  1. You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.

  2. If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.

Using number_format method in Laravel

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>

rotating axis labels in R

You need to use theme() function as follows rotating x-axis labels by 90 degrees:

ggplot(...)+...+ theme(axis.text.x = element_text(angle=90, hjust=1))

Does Django scale?

  1. "What are the largest sites built on Django today?"

    There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of the main Django project page and then a list of Django built sites at djangosites.org. Going through the lists and picking some that I know have decent traffic we see:

  2. "Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"

    Yes, see above.

  3. "Could a site like Stack Overflow run on Django?"

    My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :)

There are, of course, many more sites and bloggers of interest, but I have got to stop somewhere!


Blog post about Using Django to build high-traffic site michaelmoore.com described as a top 10,000 website. Quantcast stats and compete.com stats.


(*) The author of the edit, including such reference, used to work as outsourced developer in that project.

jQuery load first 3 elements, click "load more" to display next 5 elements

Simple and with little changes. And also hide load more when entire list is loaded.

jsFiddle here.

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#showLess').hide();
    var items =  25;
    var shown =  3;
    $('#loadMore').click(function () {
        $('#showLess').show();
        shown = $('#myList li:visible').size()+5;
        if(shown< items) {$('#myList li:lt('+shown+')').show();}
        else {$('#myList li:lt('+items+')').show();
             $('#loadMore').hide();
             }
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

Get to UIViewController from UIView?

I think there is a case when the observed needs to inform the observer.

I see a similar problem where the UIView in a UIViewController is responding to a situation and it needs to first tell its parent view controller to hide the back button and then upon completion tell the parent view controller that it needs to pop itself off the stack.

I have been trying this with delegates with no success.

I don't understand why this should be a bad idea?

Equivalent function for DATEADD() in Oracle

Not my answer :

I wasn't too happy with the answers above and some additional searching yielded this :

SELECT SYSDATE AS current_date,

       SYSDATE + 1 AS plus_1_day,

       SYSDATE + 1/24 AS plus_1_hours,

       SYSDATE + 1/24/60 AS plus_1_minutes,

       SYSDATE + 1/24/60/60 AS plus_1_seconds

FROM   dual;

which I found very helpful. From http://sqlbisam.blogspot.com/2014/01/add-date-interval-to-date-or-dateadd.html

Parsing CSV files in C#, with header

If you need only reading csv files then I recommend this library: A Fast CSV Reader
If you also need to generate csv files then use this one: FileHelpers

Both of them are free and opensource.

Eclipse : Maven search dependencies doesn't work

In your eclipse, go to Windows -> Preferences -> Maven Preferences Maven Screenshot Tick the option "Download repository index updates on startup". You may want to restart the eclipse.

Also go to Windows -> Show view -> Other -> Maven -> Maven repositories Maven Repository View Screenshot

On Maven repositories panel, Expand Global repositories then Right click on Central repositories and check "Full index enabled" option and then click on "Rebuild index".

Full Index Screenshot

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Convert a Unicode string to a string in Python (containing extra symbols)

You can use encode to ASCII if you don't need to translate the non-ASCII characters:

>>> a=u"aaaàçççñññ"
>>> type(a)
<type 'unicode'>
>>> a.encode('ascii','ignore')
'aaa'
>>> a.encode('ascii','replace')
'aaa???????'
>>>

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Passing dynamic javascript values using Url.action()

The @Url.Action() method is proccess on the server-side, so you cannot pass a client-side value to this function as a parameter. You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this:

var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;

The @Url.Action("Display", "Customer") is processed on the server-side and the rest of the string is processed on the client-side, concatenating the result of the server-side method with the client-side.

input() error - NameError: name '...' is not defined

You should use raw_input because you are using python-2.7. When you use input() on a variable (for example: s = input('Name: ')), it will execute the command ON the Python environment without saving what you wrote on the variable (s) and create an error if what you wrote is not defined.

raw_input() will save correctly what you wrote on the variable (for example: f = raw_input('Name : ')), and it will not execute it in the Python environment without creating any possible error:

input_variable = raw_input('Enter Your Name : ')
print("Your Name Is  : " + (input_variable))

How to decode viewstate

Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.

What does the "+=" operator do in Java?

The "common knowledge" of programming is that x += y is an equivalent shorthand notation of x = x + y. As long as x and y are of the same type (for example, both are ints), you may consider the two statements equivalent.

However, in Java, x += y is not identical to x = x + y in general.

If x and y are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0 (int) and y == 1.1 (double):

    int x = 0;
    x += 1.1;    // just fine; hidden cast, x == 1 after assignment
    x = x + 1.1; // won't compile! 'cannot convert from double to int'

+= performs an implicit cast, whereas for + you need to explicitly cast the second operand, otherwise you'd get a compiler error.

Quote from Joshua Bloch's Java Puzzlers:

(...) compound assignment expressions automatically cast the result of the computation they perform to the type of the variable on their left-hand side. If the type of the result is identical to the type of the variable, the cast has no effect. If, however, the type of the result is wider than that of the variable, the compound assignment operator performs a silent narrowing primitive conversion [JLS 5.1.3].

How can I get the count of milliseconds since midnight for the current?

tl;dr

You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z ? 113

  1. Get the fractional second in nanoseconds (billions).
  2. Divide by a thousand to truncate to milliseconds (thousands).

See this code run live at IdeOne.com.

Using java.time

The modern way is with the java.time classes.

Capture the current moment in UTC.

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.

More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

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.

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

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

Where to obtain the java.time classes?

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.

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:

@Bean
public Unmarshaller tmsUnmarshaller() {
    final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
    jaxb2Marshaller
            .setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
    return jaxb2Marshaller;
}

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

In JPQL the same is actually true in the spec. The JPA spec does not allow an alias to be given to a fetch join. The issue is that you can easily shoot yourself in the foot with this by restricting the context of the join fetch. It is safer to join twice.

This is normally more an issue with ToMany than ToOnes. For example,

Select e from Employee e 
join fetch e.phones p 
where p.areaCode = '613'

This will incorrectly return all Employees that contain numbers in the '613' area code but will left out phone numbers of other areas in the returned list. This means that an employee that had a phone in the 613 and 416 area codes will loose the 416 phone number, so the object will be corrupted.

Granted, if you know what you are doing, the extra join is not desirable, some JPA providers may allow aliasing the join fetch, and may allow casting the Criteria Fetch to a Join.

How can I convert String[] to ArrayList<String>

You can loop all of the array and add into ArrayList:

ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
    files.add(file);
}

Or use Arrays.asList(T... a) to do as the comment posted.

Swift error : signal SIGABRT how to solve it

In my case there was no log whatsoever.

My mistake was to push a view controller in a navigation stack that was already part of the navigation stack.

How to rotate x-axis tick labels in Pandas barplot

Try this -

plt.xticks(rotation=90)

enter image description here

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

NSURLConnection Using iOS Swift

An abbreviated version of your code worked for me,

class Remote: NSObject {

    var data = NSMutableData()

    func connect(query:NSString) {
        var url =  NSURL.URLWithString("http://www.google.com")
        var request = NSURLRequest(URL: url)
        var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
    }


     func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("didReceiveResponse")
    }

    func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
        self.data.appendData(conData)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println(self.data)
    }


    deinit {
        println("deiniting")
    }
}

This is the code I used in the calling class,

class ViewController: UIViewController {

    var remote = Remote()


    @IBAction func downloadTest(sender : UIButton) {
        remote.connect("/apis")
    }

}

You didn't specify in your question where you had this code,

var remote = Remote()
remote.connect("/apis")

If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

git push: permission denied (public key)

If you are getting 403 error here is the solution:

 The requested URL returned error: 403

As you are having your account registered with another account so you need to remove the github credentials from windows

control panel > user accounts > credential manager > Windows credentials > Generic credentials

then remove the Github keys

How can I loop through all rows of a table? (MySQL)

Mr Purple's example I used in mysql trigger like that,

begin
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
Select COUNT(*) from user where deleted_at is null INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO user_notification(notification_id,status,userId)values(new.notification_id,1,(Select userId FROM user LIMIT i,1)) ;
  SET i = i + 1;
END WHILE;
end

Why is pydot unable to find GraphViz's executables in Windows 8?

after doing all the installation of graphviz, adding to the PATH of environment variables, you need to add these two lines:

import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

Subprocess check_output returned non-zero exit status 1

For Windows users: Try deleting files: java.exe, javaw.exe and javaws.exe from Windows\System32

My issue was the java version 1.7 installed.

How to disable a link using only CSS?

You can set href attribute to javascript:void(0)

_x000D_
_x000D_
.disabled {_x000D_
  /* Disabled link style */_x000D_
  color: black;_x000D_
}
_x000D_
<a class="disabled" href="javascript:void(0)">LINK</a>
_x000D_
_x000D_
_x000D_

SQL Server 2008 Row Insert and Update timestamps

As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERTs that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP which it includes in the final INSERT to the database. You could do the same for the CREATE. You may also be able to set things up so that users cannot execute INSERT and CREATE statements other than via the stored procedures.

I have to admit that I haven't actually done this myself so I'm not at all sure of the details.

Closing Twitter Bootstrap Modal From Angular Controller

**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
  $('#btnClose').click();// this is bootstrap modal close button id that fire click event
})

--------------------------------------------------------------------------------

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()

Convert all first letter to upper case, rest lower for each word

string s = "THIS IS MY TEXT RIGHT NOW";

s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

How to use random in BATCH script?

now featuring all the colors of the dos rainbow

@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)
  ELSE set C=1&set D=A&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
set V=%D%

(IF %V% EQU 10 set V=A) 
    & (IF %V% EQU 11 set V=B)
    & (IF %V% EQU 12 set V=C)
    & (IF %V% EQU 13 set V=D) 
    & (IF %V% EQU 14 set V=E)
    & (IF %V% EQU 15 set V=F)
title %random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %V%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%
&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&IF %D% EQU 15 (set D=1)ELSE set /A D=%D%+1)
  ELSE set /A C=%C%+1)&goto Y

How to have image and text side by side

It's always worth grouping elements into sections that are relevant. In your case, a parent element that contains two columns;

  1. icon
  2. text.

http://jsfiddle.net/qMdfC/10/

HTML:

<div class='container2'>
    <img src='http://ecx.images-amazon.com/images/I/21-leKb-zsL._SL500_AA300_.png' class='iconDetails' />

    <div class="text">
        <h4>Facebook</h4>
        <p>
            fine location, GPS, coarse location
            <span>0 mins ago</span>
        </p>
    </div>
</div>

CSS:

* {
    padding:0;
    margin:0;
}
.iconDetails {
    margin:0 2%;
    float:left;
    height:40px;
    width:40px;
}
.container2 {
    width:100%;
    height:auto;
    padding:1%;
}
.text {
    float:left;
}
.text h4, .text p {
    width:100%;
    float:left;
    font-size:0.6em;
}
.text p span {
    color:#666;
}

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

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

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

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

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

How do I create a file AND any folders, if the folders don't exist?

Following code will create directories (if not exists) & then copy files.

// using System.IO;

// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(@"D:\A\", "*.*", SearchOption.AllDirectories))
{
    var fi =  new FileInfo(f);
    var di = new DirectoryInfo(fi.DirectoryName);

    // you can filter files here
    if (fi.Name.Contains("FILTER")
    {
        if (!Directory.Exists(di.FullName.Replace("A", "B"))
        {                       
            Directory.CreateDirectory(di.FullName.Replace("A", "B"));           
            File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
        }
    }
}

Can I use a binary literal in C or C++?

A few compilers (usually the ones for microcontrollers) has a special feature implemented within recognizing literal binary numbers by prefix "0b..." preceding the number, although most compilers (C/C++ standards) don't have such feature and if it is the case, here it is my alternative solution:

#define B_0000    0
#define B_0001    1
#define B_0010    2
#define B_0011    3
#define B_0100    4
#define B_0101    5
#define B_0110    6
#define B_0111    7
#define B_1000    8
#define B_1001    9
#define B_1010    a
#define B_1011    b
#define B_1100    c
#define B_1101    d
#define B_1110    e
#define B_1111    f

#define _B2H(bits)    B_##bits
#define B2H(bits)    _B2H(bits)
#define _HEX(n)        0x##n
#define HEX(n)        _HEX(n)
#define _CCAT(a,b)    a##b
#define CCAT(a,b)   _CCAT(a,b)

#define BYTE(a,b)        HEX( CCAT(B2H(a),B2H(b)) )
#define WORD(a,b,c,d)    HEX( CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))) )
#define DWORD(a,b,c,d,e,f,g,h)    HEX( CCAT(CCAT(CCAT(B2H(a),B2H(b)),CCAT(B2H(c),B2H(d))),CCAT(CCAT(B2H(e),B2H(f)),CCAT(B2H(g),B2H(h)))) )

// Using example
char b = BYTE(0100,0001); // Equivalent to b = 65; or b = 'A'; or b = 0x41;
unsigned int w = WORD(1101,1111,0100,0011); // Equivalent to w = 57155; or w = 0xdf43;
unsigned long int dw = DWORD(1101,1111,0100,0011,1111,1101,0010,1000); //Equivalent to dw = 3745774888; or dw = 0xdf43fd28;

Disadvantages (it's not such a big ones):

  • The binary numbers have to be grouped 4 by 4;
  • The binary literals have to be only unsigned integer numbers;

Advantages:

  • Total preprocessor driven, not spending processor time in pointless operations (like "?.. :..", "<<", "+") to the executable program (it may be performed hundred of times in the final application);
  • It works "mainly in C" compilers and C++ as well (template+enum solution works only in C++ compilers);
  • It has only the limitation of "longness" for expressing "literal constant" values. There would have been earlyish longness limitation (usually 8 bits: 0-255) if one had expressed constant values by parsing resolve of "enum solution" (usually 255 = reach enum definition limit), differently, "literal constant" limitations, in the compiler allows greater numbers;
  • Some other solutions demand exaggerated number of constant definitions (too many defines in my opinion) including long or several header files (in most cases not easily readable and understandable, and make the project become unnecessarily confused and extended, like that using "BOOST_BINARY()");
  • Simplicity of the solution: easily readable, understandable and adjustable for other cases (could be extended for grouping 8 by 8 too);

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

You could use a recursive scalar function:-

set nocount on

create table location (
    id int,
    name varchar(50),
    parent int
)
insert into location values
    (1,'france',null),
    (2,'paris',1),
    (3,'belleville',2),
    (4,'lyon',1),
    (5,'vaise',4),
    (6,'united kingdom',null),
    (7,'england',6),
    (8,'manchester',7),
    (9,'fallowfield',8),
    (10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
    declare @returnValue varchar(1024)=''
    declare @parent int
    select @returnValue+=' > '+name,@parent=parent
    from location
    where id=@child
    if @parent is not null
        set @returnValue=dbo.breadcrumb(@parent)+@returnValue
    return @returnValue
end
go

declare @location int=1
while @location<=10 begin
    print dbo.breadcrumb(@location)+' >'
    set @location+=1
end

produces:-

 > france >
 > france > paris >
 > france > paris > belleville >
 > france > lyon >
 > france > lyon > vaise >
 > united kingdom >
 > united kingdom > england >
 > united kingdom > england > manchester >
 > united kingdom > england > manchester > fallowfield >
 > united kingdom > england > manchester > withington >

How to create web service (server & Client) in Visual Studio 2012?

WCF is a newer technology that is a viable alternative in many instances. ASP is great and works well, but I personally prefer WCF. And you can do it in .Net 4.5.

WCF Project

enter image description here

Create a new project. enter image description here Right-Click on the project in solution explorer, select "Add Service Reference" enter image description here

Create a textbox and button in the new application. Below is my click event for the button:

private void btnGo_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client testClient = new ServiceReference1.Service1Client();
        //Add error handling, null checks, etc...
        int iValue = int.Parse(txtInput.Text);
        string sResult = testClient.GetData(iValue).ToString();
        MessageBox.Show(sResult);
    }

And you're done. enter image description here

How to save a Python interactive session?

The %history command is awesome, but unfortunately it won't let you save things that were %paste 'd into the sesh. To do that I think you have to do %logstart at the beginning (although I haven't confirmed this works).

What I like to do is

%history -o -n -p -f filename.txt

which will save the output, line numbers, and '>>>' before each input (o, n, and p options). See the docs for %history here.

How to write a file or data to an S3 object using boto3

You no longer have to convert the contents to binary before writing to the file in S3. The following example creates a new text file (called newfile.txt) in an S3 bucket with string contents:

import boto3

s3 = boto3.resource(
    's3',
    region_name='us-east-1',
    aws_access_key_id=KEY_ID,
    aws_secret_access_key=ACCESS_KEY
)
content="String content to write to a new S3 file"
s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)

Converting Python dict to kwargs?

** operator would be helpful here.

** operator will unpack the dict elements and thus **{'type':'Event'} would be treated as type='Event'

func(**{'type':'Event'}) is same as func(type='Event') i.e the dict elements would be converted to the keyword arguments.

FYI

* will unpack the list elements and they would be treated as positional arguments.

func(*['one', 'two']) is same as func('one', 'two')

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

Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as neeeded.
 * https://stackoverflow.com/a/826027/1202830
 */

#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */

#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t; 
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */

Detect Click into Iframe using JavaScript

This works for me on all browsers (included Firefox)

https://gist.github.com/jaydson/1780598

https://jsfiddle.net/sidanmor/v6m9exsw/

_x000D_
_x000D_
var myConfObj = {_x000D_
  iframeMouseOver : false_x000D_
}_x000D_
window.addEventListener('blur',function(){_x000D_
  if(myConfObj.iframeMouseOver){_x000D_
    console.log('Wow! Iframe Click!');_x000D_
  }_x000D_
});_x000D_
_x000D_
document.getElementById('idanmorblog').addEventListener('mouseover',function(){_x000D_
   myConfObj.iframeMouseOver = true;_x000D_
});_x000D_
document.getElementById('idanmorblog').addEventListener('mouseout',function(){_x000D_
    myConfObj.iframeMouseOver = false;_x000D_
});
_x000D_
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
_x000D_
_x000D_
_x000D_

<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>

Resizing an Image without losing any quality

Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.

How to plot a histogram using Matplotlib in Python with a list of data?

This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.

First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.

Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.

However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.

Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.

If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability) with maybe binning option, and use of x-labels already available is suspicious.

Then bar plot should not be used as histogram but rather simply

import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375, 
  0.373117033603708, 0.36813186813186816, 0.32517482517482516, 
  0.4175257731958763, 0.41025641025641024, 0.39408866995073893, 
  0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327, 
  0.35398230088495575]
plt.hist(probability)
plt.show()

with the results

enter image description here

matplotlib in such case arrives by default with the following histogram values

(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
 array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
        0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
        0.42028986]),
 <a list of 10 Patch objects>)

the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.

One can check they they are equally spaced,

x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
  print(left, right, right-left)

enter image description here

Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram

plt.hist(probability, bins=3)

enter image description here

with the plot data "behind the bars" being

enter image description here

The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).

java : convert float to String and String to float

This is a possible answer, this will also give the precise data, just need to change the decimal point in the required form.

public class TestStandAlone {

    /**
     * 

This method is to main

* @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Output will be

f1 --> 152.32
s1 152.32

Loading a .json file into c# program

See Microsofts JavaScriptSerializer

The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

Namespace: System.Web.Script.Serialization

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

How to get WordPress post featured image URL

Simply inside the loop write <?php the_post_thumbnail_url(); ?> as shown below:-

$args=array('post_type' => 'your_custom_post_type_slug','order' => 'DESC','posts_per_page'=> -1) ;
$the_qyery= new WP_Query($args);

if ($the_qyery->have_posts()) :
    while ( $the_qyery->have_posts() ) : $the_qyery->the_post();?>

<div class="col col_4_of_12">
    <div class="article_standard_view">
        <article class="item">
            <div class="item_header">
                <a href="<?php the_permalink(); ?>"><img src="<?php the_post_thumbnail_url(); ?>" alt="Post"></a>
            </div>

        </article>
    </div>
</div>            
<?php endwhile; endif; ?>

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

Newline in string attribute

Note that to do this you need to do it in the Text attribute you cannot use the content like

<TextBlock>Stuff on line1&#x0a;Stuff on line 2</TextBlock>

Spring Boot Remove Whitelabel Error Page

I am using Spring Boot version 2.1.2 and the errorAttributes.getErrorAttributes() signature didn't work for me (in acohen's response). I wanted a JSON type response so I did a little digging and found this method did exactly what I needed.

I got most of my information from this thread as well as this blog post.

First, I created a CustomErrorController that Spring will look for to map any errors to.

package com.example.error;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "error";

    @Value("${debug}")
    private boolean debug;

    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(PATH)
    @ResponseBody
    public CustomHttpErrorResponse error(WebRequest request, HttpServletResponse response) {
        return new CustomHttpErrorResponse(response.getStatus(), getErrorAttributes(request));
    }

    public void setErrorAttributes(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    private Map<String, Object> getErrorAttributes(WebRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.putAll(this.errorAttributes.getErrorAttributes(request, this.debug));
        return map;
    }
}

Second, I created a CustomHttpErrorResponse class to return the error as JSON.

package com.example.error;

import java.util.Map;

public class CustomHttpErrorResponse {

    private Integer status;
    private String path;
    private String errorMessage;
    private String timeStamp;
    private String trace;

    public CustomHttpErrorResponse(int status, Map<String, Object> errorAttributes) {
        this.setStatus(status);
        this.setPath((String) errorAttributes.get("path"));
        this.setErrorMessage((String) errorAttributes.get("message"));
        this.setTimeStamp(errorAttributes.get("timestamp").toString());
        this.setTrace((String) errorAttributes.get("trace"));
    }

    // getters and setters
}

Finally, I had to turn off the Whitelabel in the application.properties file.

server.error.whitelabel.enabled=false

This should even work for xml requests/responses. But I haven't tested that. It did exactly what I was looking for since I was creating a RESTful API and only wanted to return JSON.

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I recommend using this:

  1. Retrieve the father Intent.

    Intent intentParent = getIntent();
    
  2. Convey the message directly.

    setResult(RESULT_OK, intentParent);
    

This prevents the loss of its activity which would generate a null data error.

Correct way to remove plugin from Eclipse

Correct way to remove install plug-in from Eclipse/STS :

Go to install folder of eclipse ----> plugin --> select required plugin and remove it.

Ex-

Step 1. 
E:\springsource\sts-3.4.0.RELEASE\plugins

Step 2. 
select and remove related plugins jars.

Find document with array that contains a specific value

I know this topic is old, but for future people who could wonder the same question, another incredibly inefficient solution could be to do:

PersonModel.find({$where : 'this.favouriteFoods.indexOf("sushi") != -1'});

This avoids all optimisations by MongoDB so do not use in production code.

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Cast received object to a List<object> or IEnumerable<object>

Do you actually need more information than plain IEnumerable gives you? Just cast it to that and use foreach with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable (or IList to access it like a list) works very well.

How to set session timeout in web.config

If you want to set the timeout to 20 minutes, use something like this:

    <configuration>
      <system.web>
         <sessionState timeout="20"></sessionState>
      </system.web>
    </configuration>

Generating random strings with T-SQL

I came across this blog post first, then came up with the following stored procedure for this that I'm using on a current project (sorry for the weird formatting):

CREATE PROCEDURE [dbo].[SpGenerateRandomString]
@sLength tinyint = 10,
@randomString varchar(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE @counter tinyint
DECLARE @nextChar char(1)
SET @counter = 1
SET @randomString = ”

WHILE @counter <= @sLength
BEGIN
SELECT @nextChar = CHAR(48 + CONVERT(INT, (122-48+1)*RAND()))

IF ASCII(@nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96)
BEGIN
SELECT @randomString = @randomString + @nextChar
SET @counter = @counter + 1
END
END
END

convert string array to string

Like this:

string str= test[0]+test[1];

You can also use a loop:

for(int i=0; i<2; i++)
    str += test[i];

how does array[100] = {0} set the entire array to 0?

It depends where you put this initialisation.

If the array is static as in

char array[100] = {0};

int main(void)
{
...
}

then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.

If your array is auto, then it is another story.

int foo(void)
{
char array[100] = {0};
...
}

In this case at every call of the function foo you will have a hidden memset.

The code above is equivalent to

int foo(void)
{ 
char array[100];

memset(array, 0, sizeof(array));
....
}

and if you omit the initializer your array will contain random data (the data of the stack).

If your local array is declared static like in

int foo(void)
{ 
static char array[100] = {0};
...
}

then it is technically the same case as the first one.

MySQL high CPU usage

If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)

update to python 3.7 using anaconda

run conda navigator, you can upgrade your packages easily in the friendly GUI

Node / Express: EADDRINUSE, Address already in use - Kill server

This means you have two node servers running on the same port ,if one is running on port let say 3000 change the other one to another port lets say 3001 and everything will work well

How to format a phone number with jQuery

To expand on Cruz Nunez code and add continual formatting, plus include some international phone number formats.

    $('#phone').on('input', function() {
      var number = $(this).val().replace(/[^\d]/g, '');
      if (number.length == 3) {
        number = number.replace(/(\d{3})/, "$1-");
      } else if (number.length == 4) {
        number = number.replace(/(\d{3})(\d{1})/, "$1-$2");
      } else if (number.length == 5) {
        number = number.replace(/(\d{3})(\d{2})/, "$1-$2");
      } else if (number.length == 6) {
        number = number.replace(/(\d{3})(\d{3})/, "$1-$2-");
      } else if (number.length == 7) {
        number = number.replace(/(\d{3})(\d{3})(\d{1})/, "$1-$2-$3");
      } else if (number.length == 8) {
        number = number.replace(/(\d{4})(\d{4})/, "$1-$2");
      } else if (number.length == 9) {
        number = number.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3");
      } else if (number.length == 10) {
        number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
      } else if (number.length == 11) {
        number = number.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      } else if (number.length == 12) {
        number = number.replace(/(\d{2})(\d{3})(\d{3})(\d{4})/, "$1-$2-$3-$4");
      }
      $(this).val(number);
    });

How do I run a simple bit of code in a new thread?

The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.

System.Threading.ThreadPool.QueueUserWorkItem(delegate {
    DoSomethingThatDoesntInvolveAControl();
}, null);

Append values to query string

The following solution works for ASP.NET 5 (vNext) and it uses QueryHelpers class to build a URI with parameters.

    public Uri GetUri()
    {
        var location = _config.Get("http://iberia.com");
        Dictionary<string, string> values = GetDictionaryParameters();

        var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(location, values);
        return new Uri(uri);
    }

    private Dictionary<string,string> GetDictionaryParameters()
    {
        Dictionary<string, string> values = new Dictionary<string, string>
        {
            { "param1", "value1" },
            { "param2", "value2"},
            { "param3", "value3"}
        };
        return values;
    }

The result URI would have http://iberia.com?param1=value1&param2=value2&param3=value3

How to call one shell script from another shell script?

There are some problems to import functions from other file.
First: You needn't to do this file executable. Better not to do so! just add

. file

to import all functions. And all of them will be as if they are defined in your file.
Second: You may be define the function with the same name. It will be overwritten. It's bad. You may declare like that

declare -f new_function_name=old_function_name 

and only after that do import. So you may call old function by new name.
Third: You may import only full list of functions defined in file. If some not needed you may unset them. But if you rewrite your functions after unset they will be lost. But if you set reference to it as described above you may restore after unset with the same name.
Finally In common procedure of import is dangerous and not so simple. Be careful! You may write script to do this more easier and safe. If you use only part of functions(not all) better split them in different files. Unfortunately this technique not made well in bash. In python for example and some other script languages it's easy and safe. Possible to make partial import only needed functions with its own names. We all want that in next bush versions will be done the same functionality. But now We must write many additional cod so as to do what you want.

How to parse the AndroidManifest.xml file inside an .apk package

You can use axml2xml.pl tool developed a while ago within android-random project. It will generate the textual manifest file (AndroidManifest.xml) from the binary one.

I'm saying "textual" and not "original" because like many reverse-engineering tools this one isn't perfect and the result will not be complete. I presume either it was never feature complete or simply not forward-compatible (with newer binary encoding scheme). Whatever the reason, axml2xml.pl tool will not be able to extract all the attribute values correctly. Such attributes are minSdkVersion, targetSdkVersion and basically all attributes that are referencing resources (like strings, icons, etc.), i.e. only class names (of activities, services, etc.) are extracted correctly.

However, you can still find these missing information by running aapt tool on the original Android app file (.apk):

aapt l -a <someapp.apk>

How do you get AngularJS to bind to the title attribute of an A tag?

It looks like ng-attr is a new directive in AngularJS 1.1.4 that you can possibly use in this case.

<!-- example -->
<a ng-attr-title="{{product.shortDesc}}"></a>

However, if you stay with 1.0.7, you can probably write a custom directive to mirror the effect.

How can I know if a branch has been already merged into master?

I am using the following bash function like: git-is-merged develop feature/new-feature

git-is-merged () {
  merge_destination_branch=$1
  merge_source_branch=$2

  merge_base=$(git merge-base $merge_destination_branch $merge_source_branch)
  merge_source_current_commit=$(git rev-parse $merge_source_branch)
  if [[ $merge_base = $merge_source_current_commit ]]
  then
    echo $merge_source_branch is merged into $merge_destination_branch
    return 0
  else
    echo $merge_source_branch is not merged into $merge_destination_branch
    return 1
  fi
}

Cannot find firefox binary in PATH. Make sure firefox is installed

Make sure that firefox must install on default place like ->(c:/Program Files (x86)/mozilla firefox OR c:/Program Files/mozilla firefox, note: at the time of firefox installation do not change the path so let it installing in default path) If firefox is installed on some other place then selenium show those error.

If you have set your firefox in Systems(Windows) environment variable then either remove it or update it with new firefox version path.

If you want to use Firefox in any other place then use below code:-

As FirefoxProfile is depricated we need to use FirefoxOptions as below:

New Code:

File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);   
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));

The full working code of above code is as below:

System.setProperty("webdriver.gecko.driver","D:\\Workspace\\demoproject\\src\\lib\\geckodriver.exe");
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);   
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.co.in/");

Download geckodriver for firefox from below URL:

https://github.com/mozilla/geckodriver/releases

Old Code which will work for old selenium jars versions

File pathBinary = new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();       
WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile);

how to get the first and last days of a given month

Try this , if you are using PHP 5.3+, in php

$query_date = '2010-02-04';
$date = new DateTime($query_date);
//First day of month
$date->modify('first day of this month');
$firstday= $date->format('Y-m-d');
//Last day of month
$date->modify('last day of this month');
$lastday= $date->format('Y-m-d');

For finding next month last date, modify as follows,

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

and so on..

Adding sheets to end of workbook in Excel (normal method not working?)

Try this

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

Formatting DataBinder.Eval data

Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'

This works for the format as you want

HTML - how to make an entire DIV a hyperlink?

You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:

<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>

and the example CSS:

#smallbox {
    cursor: pointer;
}

So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!

Append lines to a file using a StreamWriter

Replace this line:

StreamWriter sw = new StreamWriter("c:/file.txt");

with this code:

StreamWriter sw = File.AppendText("c:/file.txt");

and then write your line to the text file like this:

sw.WriteLine("text content");

subquery in FROM must have an alias

add an ALIAS on the subquery,

SELECT  COUNT(made_only_recharge) AS made_only_recharge
FROM    
    (
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER = '0130'
        EXCEPT
        SELECT DISTINCT (identifiant) AS made_only_recharge
        FROM cdr_data
        WHERE CALLEDNUMBER != '0130'
    ) AS derivedTable                           -- <<== HERE

How to vertically align an image inside a div

Imagine you have

<div class="wrap">
    <img src="#">
</div>

And css:

.wrap {
    display: flex;
}
.wrap img {
    object-fit: contain;
}

Purpose of "%matplotlib inline"

To explain it clear:

If you don't like it like this:

enter image description here

add %matplotlib inline

enter image description here

and there you have it in your jupyter notebook.

How to hide columns in HTML table?

you can also use:

<td style="visibility:hidden;">
or
<td style="visibility:collapse;">

The difference between them that "hidden" hides the cell but it holds the space but with "collapse" the space is not held like display:none. This is significant when hidding a whole column or row.

NSRange to Range<String.Index>

A riff on the great answer by @Emilie, not a replacement/competing answer.
(Xcode6-Beta5)

var original    = "This is a test"
var replacement = "!"

var startIndex = advance(original.startIndex, 1) // Start at the second character
var endIndex   = advance(startIndex, 2) // point ahead two characters
var range      = Range(start:startIndex, end:endIndex)
var final = original.stringByReplacingCharactersInRange(range, withString:replacement)

println("start index: \(startIndex)")
println("end index:   \(endIndex)")
println("range:       \(range)")
println("original:    \(original)")
println("final:       \(final)")

Output:

start index: 4
end index:   7
range:       4..<7
original:    This is a test
final:       !his is a test

Notice the indexes account for multiple code units. The flag (REGIONAL INDICATOR SYMBOL LETTERS ES) is 8 bytes and the (FACE WITH TEARS OF JOY) is 4 bytes. (In this particular case it turns out that the number of bytes is the same for UTF-8, UTF-16 and UTF-32 representations.)

Wrapping it in a func:

func replaceString(#string:String, #with:String, #start:Int, #length:Int) ->String {
    var startIndex = advance(original.startIndex, start) // Start at the second character
    var endIndex   = advance(startIndex, length) // point ahead two characters
    var range      = Range(start:startIndex, end:endIndex)
    var final = original.stringByReplacingCharactersInRange(range, withString: replacement)
    return final
}

var newString = replaceString(string:original, with:replacement, start:1, length:2)
println("newString:\(newString)")

Output:

newString: !his is a test

Why use double indirection? or Why use pointers to pointers?

One thing I use them for constantly is when I have an array of objects and I need to perform lookups (binary search) on them by different fields.
I keep the original array...

int num_objects;
OBJECT *original_array = malloc(sizeof(OBJECT)*num_objects);

Then make an array of sorted pointers to the objects.

int compare_object_by_name( const void *v1, const void *v2 ) {
  OBJECT *o1 = *(OBJECT **)v1;
  OBJECT *o2 = *(OBJECT **)v2;
  return (strcmp(o1->name, o2->name);
}

OBJECT **object_ptrs_by_name = malloc(sizeof(OBJECT *)*num_objects);
  int i = 0;
  for( ; i<num_objects; i++)
    object_ptrs_by_name[i] = original_array+i;
  qsort(object_ptrs_by_name, num_objects, sizeof(OBJECT *), compare_object_by_name);

You can make as many sorted pointer arrays as you need, then use a binary search on the sorted pointer array to access the object you need by the data you have. The original array of objects can stay unsorted, but each pointer array will be sorted by their specified field.

How can you strip non-ASCII characters from a string? (in C#)

string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

What is the list of supported languages/locales on Android?

First we need to plan how the application will render differently in different locals. Here it shows example, where the text string and images have to go.

de-rDE German / Germany res/values-de/ res/drawable-de-rDE/ 
fr-rFR French / France res/values-fr/ res/drawable-fr-rFR/ 
fr-rCA French / Canada res/values-fr/ res/drawable-fr-rCA/ 
en-rCA English / Canada (res/values/) res/drawable-en-rCA/ 
ja-rJP Japanese / Japan res/values-ja/ res/drawable-ja-rJP/ 
en-rUS English / United States (res/values/) res/drawable-en-rUS/ 

For more info you can see the page Localization

Android Studio: Application Installation Failed

If you do all of things above and still get stuck, just try reopening your Android Studio.

How to delete a selected DataGridViewRow and update a connected database table?

if(this.dgvpurchase.Rows.Count>1)
{
    if(this.dgvpurchase.CurrentRow.Index<this.dgvpurchase.Rows.Count)
    {
        this.txtname.Text = this.dgvpurchase.CurrentRow.Cells[1].Value.ToString();
        this.txttype.Text = this.dgvpurchase.CurrentRow.Cells[2].Value.ToString();
        this.cbxcode.Text = this.dgvpurchase.CurrentRow.Cells[3].Value.ToString();
        this.cbxcompany.Text = this.dgvpurchase.CurrentRow.Cells[4].Value.ToString();
        this.dtppurchase.Value = Convert.ToDateTime(this.dgvpurchase.CurrentRow.Cells[5].Value);
        this.txtprice.Text = this.dgvpurchase.CurrentRow.Cells[6].Value.ToString();
        this.txtqty.Text = this.dgvpurchase.CurrentRow.Cells[7].Value.ToString();
        this.txttotal.Text = this.dgvpurchase.CurrentRow.Cells[8].Value.ToString();
        this.dgvpurchase.Rows.RemoveAt(this.dgvpurchase.CurrentRow.Index);
        refreshid();
    }
}

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I believe this error caused because of downloading SRC instead of BINARY from Maven site. Please make sure to download Binary zip.

Because the below path, you will get only when you download SRC:

M2_HOME C:\apache-maven-3.0.4\apache-maven\src

enter image description here

Get index of element as child relative to parent

Delegate and Live are easy to use but if you won't have any more li:s added dynamically you could use event delagation with normal bind/click as well. There should be some performance gain using this method since the DOM won't have to be monitored for new matching elements. Haven't got any actual numbers but it makes sense :)

$("#wizard").click(function (e) {
    var source = $(e.target);
    if(source.is("li")){
        // alert index of li relative to ul parent
        alert(source.index());
    }
});

You could test it at jsFiddle: http://jsfiddle.net/jimmysv/4Sfdh/1/

Dynamically Add Images React Webpack

UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.

With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:

This will NOT work. :

const myImg = './cute.jpg'
<img src={require(myImg)} />

To fix this, just use template strings instead :

const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />

webpack.config.js :

var HtmlWebpackPlugin =  require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry : './src/app.js',
  output : {
    path : './dist',
    filename : 'app.bundle.js'
  },
  plugins : [
  new ExtractTextWebpackPlugin('app.bundle.css')],
  module : {
    rules : [{
      test : /\.css$/,
      use : ExtractTextWebpackPlugin.extract({
        fallback : 'style-loader',
        use: 'css-loader'
      })
    },{
      test: /\.js$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015']
      }
    },{
      test : /\.jpg$/,
      exclude: /(node_modules)/,
      loader : 'file-loader'
    }]
  }
}

urlencoded Forward slash is breaking URL

On my hosting account this problem was caused by a ModSecurity rule that was set for all accounts automatically. Upon my reporting this problem, their admin quickly removed this rule for my account.

Is it possible to serialize and deserialize a class in C++?

If you want simple and best performance and don't care about backward data compatibility, try HPS, it's lightweight, much faster than Boost, etc, and much easier to use than Protobuf, etc.

Example:

std::vector<int> data({22, 333, -4444});
std::string serialized = hps::serialize_to_string(data);
auto parsed = hps::parse_from_string<std::vector<int>>(serialized);

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

How to convert a Drawable to a Bitmap?

A Drawable can be drawn onto a Canvas, and a Canvas can be backed by a Bitmap:

(Updated to handle a quick conversion for BitmapDrawables and to ensure that the Bitmap created has a valid size)

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Calling virtual functions inside constructors

Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual . .another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.

  1. Virtual functions are used to assign value dynamically,as constructors are static,so we can not make them virtual.

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

Java Strings: "String s = new String("silly");"

In most versions of the JDK the two versions will be the same:

String s = new String("silly");

String s = "No longer silly";

Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.

To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.

I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.

UPDATE: I was wrong! Based on a down vote and comment attached I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!

Angularjs dynamic ng-pattern validation

_x000D_
_x000D_
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
_x000D_
_x000D_

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

The entity cannot be constructed in a LINQ to Entities query

Another simple way :)

public IQueryable<Product> GetProducts(int categoryID)
{
    var productList = db.Products
        .Where(p => p.CategoryID == categoryID)
        .Select(item => 
            new Product
            {
                Name = item.Name
            })
        .ToList()
        .AsQueryable(); // actually it's not useful after "ToList()" :D

    return productList;
}

How to set Status Bar Style in Swift 3

If you're using modal presentation you need to set:

viewController.modalPresentationCapturesStatusBarAppearance = true

Error: «Could not load type MvcApplication»

In my case issue was I renamed class Global to MvcApplication. When renaming it has to be changed on all places, otherwise app is looking for Global class in given namespace.

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

Excel compare two columns and highlight duplicates

Don't wana do soo much work guyss.. Just Press Ctr and select Colum one and Press Ctr and select colum two. Then click conditional formatting -> Highlight Cell Rules -> Equel To.

and thats it. your done. :)

Android Studio: Can't start Git

The path for your git is invalid. Copy the path from File -> Settings -> Version Control -> Git and search that folder and you can see the path to your Git is not valid. Reset the path with correct location and test it. The error should be gone.

Add another class to a div

I am facing the same issue. If parent element is hidden then after showing the element chosen drop down are not showing. This is not a perfect solution but it solved my issue. After showing the element you can use following code.

function onshowelement() { $('.chosen').chosen('destroy'); $(".chosen").chosen({ width: '100%' }); }

How do I convert a string to enum in TypeScript?

other variation can be

const green= "Green";

const color : Color = Color[green] as Color;

Regex for parsing directory and filename

What about this?

[/]{0,1}([^/]+[/])*([^/]*)

Deterministic :

((/)|())([^/]+/)*([^/]*)

Strict :

^[/]{0,1}([^/]+[/])*([^/]*)$
^((/)|())([^/]+/)*([^/]*)$

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

Sleep Command in T-SQL?

You can also "WAITFOR" a "TIME":

    RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
    WAITFOR TIME '16:43:30.000'
    RAISERROR('I waited!', 0, 1) WITH NOWAIT

How to set background color of a button in Java GUI?

Use the setBackground method to set the background and setForeground to change the colour of your text. Note however, that putting grey text over a black background might make your text a bit tough to read.

Add Auto-Increment ID to existing table?

ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT

the integer parameter is based on my default sql setting have a nice day

User GETDATE() to put current date into SQL variable

You don't need the SELECT

DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()

How to call a function from a string stored in a variable?

The easiest way to call a function safely using the name stored in a variable is,

//I want to call method deploy that is stored in functionname 
$functionname = 'deploy';

$retVal = {$functionname}('parameters');

I have used like below to create migration tables in Laravel dynamically,

foreach(App\Test::$columns as $name => $column){
        $table->{$column[0]}($name);
}

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

JUNIT testing void methods

If your method is void and you want to check for an exception, you could use expected: https://weblogs.java.net/blog/johnsmart/archive/2009/09/27/testing-exceptions-junit-47

Concatenate multiple node values in xpath

I used concat method and works well.

concat(//SomeElement/text(),'_',//OtherElement/text())

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

Happen with me because I ran git config core.autocrlf true and I forgot to rever back.

After that, when I checkout/pull new code, all LF (break line in Unix) was replaced by CRLF (Break line in Windows).

I ran linter, and all error messages are Expected linebreaks to be 'LF' but found 'CRLF'

To fix the issue, I checked autocrlf value by running git config --list | grep autocrlf and I got:

core.autocrlf=true
core.autocrlf=false

I edited the global GIT config ~/.gitconfig and replaced autocrlf = true by autocrlf = false.

After that, I went to my project and do the following (assuming the code in src/ folder):

CURRENT_BRANCH=$(git branch | grep \* | cut -d ' ' -f2);
rm -rf src/*
git checkout $CURRENT_BRANCH src/

Defining a percentage width for a LinearLayout?

As a latest update to android in 2015, Google has included percent support library

com.android.support:percent:23.1.0

You can refer to this site for example of using it

https://github.com/JulienGenoud/android-percent-support-lib-sample

Gradle:

dependencies {
    compile 'com.android.support:percent:22.2.0'
}

In the layout:

<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/top_left"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:background="#ff44aacc"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="70%" />

    <View
        android:id="@+id/top_right"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/top_left"
        android:background="#ffe40000"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="30%" />


    <View
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/top_left"
        android:background="#ff00ff22"
        app:layout_heightPercent="80%" />
</android.support.percent.PercentRelativeLayout>

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Check if an array item is set in JS

if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

How to comment in Vim's config files: ".vimrc"?

You can add comments in Vim's configuration file by either:

" brief descriptiion of command

or:

"" commended command

Taken from here

Rebuild Docker container on file changes

Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build . So that images get rebuild and refreshed

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

How to code a very simple login system with java

import java.util.Scanner;

public class LoginMain {

public static void main(String[] args) {

    String Username;
    String Password;

    Password = "123";
    Username = "wisdom";

    Scanner input1 = new Scanner(System.in);
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();

    if (username.equals(Username) && password.equals(Password)) {

        System.out.println("Access Granted! Welcome!");
    }

    else if (username.equals(Username)) {
        System.out.println("Invalid Password!");
    } else if (password.equals(Password)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Invalid Username & Password!");
    }

What is the difference between Normalize.css and Reset CSS?

Normalize.css :Every browser is coming with some default css styles that will, for example, add padding around a paragraph or title.If you add the normalize style sheet all those browser default rules will be reset so for this instance 0px padding on tags.Here is a couple of links for more details: https://necolas.github.io/normalize.css/ http://nicolasgallagher.com/about-normalize-css/

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

Real escape string and PDO

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

How do you normalize a file path in Bash?

I'm late to the party, but this is the solution I've crafted after reading a bunch of threads like this:

resolve_dir() {
        (builtin cd `dirname "${1/#~/$HOME}"`'/'`basename "${1/#~/$HOME}"` 2>/dev/null; if [ $? -eq 0 ]; then pwd; fi)
}

This will resolve the absolute path of $1, play nice with ~, keep symlinks in the path where they are, and it won't mess with your directory stack. It returns the full path or nothing if it doesn't exist. It expects $1 to be a directory and will probably fail if it's not, but that's an easy check to do yourself.

Retrieving a List from a java.util.stream.Stream in Java 8

Updated:

Another approach is to use Collectors.toList:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toList());

Previous Solution:

Another approach is to use Collectors.toCollection:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toCollection(ArrayList::new));

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

HTML: How to limit file upload to be only images?

Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*". But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.

 <div class="col-sm-8 img-upload-section">
     <input name="image3" type="file" accept="image/*" id="menu_images"/>
     <img id="menu_image" class="preview_img" />
     <input type="submit" value="Submit" />
 </div> 

Here on the change event we first check the size of the image. And in the second if condition we check whether or not it is an image file.

this.files[0].type.indexOf("image") will be -1 if it is not an image file.

document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();     
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();         
        return false;
    }   
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show(); 
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

Prevent row names to be written to file when using write.csv

For completeness, write_csv() from the readr package is faster and never writes row names

# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")

If you need to write big data out, use fwrite() from the data.table package. It's much faster than both write.csv and write_csv

# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")

Below is a benchmark that Edouard published on his site

microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
               write_csv(data, "readr_file.csv"),
               fwrite(data, "datatable_file.csv"),
               times = 10, unit = "s")

## Unit: seconds
##                                              expr        min         lq       mean     median         uq        max neval
##  write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311    10
##                 write_csv(data, "readr_file.csv")  3.6742610  3.7999409  3.8572456  3.8690681  3.8991995  4.0637453    10
##                fwrite(data, "datatable_file.csv")  0.3976728  0.4014872  0.4097876  0.4061506  0.4159007  0.4355469    10

What is the Auto-Alignment Shortcut Key in Eclipse?

Ctrl+Shift+F to invoke the Auto Formatter

Ctrl+I to indent the selected part (or all) of you code.

How do I push a local Git branch to master branch in the remote?

Follow the below steps for push the local repo into Master branchenter code here

$git status

How can I get LINQ to return the object which has the max value for a given property?

In LINQ you can solve it the following way:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

Simply quote your variable:

[ -e "$VAR" ]

This evaluates to [ -e "" ] if $VAR is empty.

Your version does not work because it evaluates to [ -e ]. Now in this case, bash simply checks if the single argument (-e) is a non-empty string.

From the manpage:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...

1 argument

The expression is true if and only if the argument is not null.

(Also, this solution has the additional benefit of working with filenames containing spaces)

Is there a float input type in HTML5?

Based on this answer

<input type="text" id="sno" placeholder="Only float with dot !"   
   onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||  
   event.charCode == 46 || event.charCode == 0 ">

Meaning :

Char code :

  • 48-57 equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • 0 is Backspace(otherwise need refresh page on Firefox)
  • 46 is dot

&& is AND , || is OR operator.

if you try float with comma :

<input type="text" id="sno" placeholder="Only float with comma !"   
     onkeypress="return (event.charCode >= 48 && event.charCode <= 57) ||  
     event.charCode == 44 || event.charCode == 0 ">

Supported Chromium and Firefox (Linux X64)(other browsers I does not exist.)

Shrink a YouTube video to responsive width

I make this with simple css as follows

HTML CODE

<iframe id="vid" src="https://www.youtube.com/embed/RuD7Se9jMag" frameborder="0" allowfullscreen></iframe>

CSS CODE

<style type="text/css">
#vid {

max-width: 100%;
height: auto;

}

How do emulators work and how are they written?

A guy named Victor Moya del Barrio wrote his thesis on this topic. A lot of good information on 152 pages. You can download the PDF here.

If you don't want to register with scribd, you can google for the PDF title, "Study of the techniques for emulation programming". There are a couple of different sources for the PDF.

.htaccess not working apache

By default, Apache prohibits using an .htaccess file to apply rewrite rules, so

Step 1 — Enabling mod_rewrite (if not Enabled) First, we need to activate mod_rewrite. It's available but not enabled with a clean Apache 2 installation.

$ sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we'll use to define rewrite rules for redirects.

Step 2 — Setting Up .htaccess Open the default Apache configuration file using nano or your favorite text editor.

$ sudo nano /etc/apache2/sites-available/000-default.conf

Inside that file, you will find a block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.

/etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted
    </Directory>

    . . . 
</VirtualHost>

Save and close the file. To put these changes into effect, restart Apache.

$ sudo systemctl restart apache2

Done. Your .htacess should work. This link may actually help somebody https://www.digitalocean.com/community/tutorials/how-to-rewrite-urls-with-mod_rewrite-for-apache-on-ubuntu-16-04

How to get some values from a JSON string in C#?

my string

var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}

Following code to get guid:

var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

I got below error :

Found the synthetic property @collapse. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.

I follow the accepted answer by Ploppy and it resolved my problem.

Here are the steps:

1.
    import { trigger, state, style, transition, animate } from '@angular/animations';
    Or 
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

2. Define the same in the import array in the root module.

It will resolve the error. Happy coding!!

Determining complexity for recursive functions (Big O notation)

The time complexity, in Big O notation, for each function:


int recursiveFun1(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun1(n-1);
}

This function is being called recursively n times before reaching the base case so its O(n), often called linear.


int recursiveFun2(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun2(n-5);
}

This function is called n-5 for each time, so we deduct five from n before calling the function, but n-5 is also O(n). (Actually called order of n/5 times. And, O(n/5) = O(n) ).


int recursiveFun3(int n)
{
    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun3(n/5);
}

This function is log(n) base 5, for every time we divide by 5 before calling the function so its O(log(n))(base 5), often called logarithmic and most often Big O notation and complexity analysis uses base 2.


void recursiveFun4(int n, int m, int o)
{
    if (n <= 0)
    {
        printf("%d, %d\n",m, o);
    }
    else
    {
        recursiveFun4(n-1, m+1, o);
        recursiveFun4(n-1, m, o+1);
    }
}

Here, it's O(2^n), or exponential, since each function call calls itself twice unless it has been recursed n times.



int recursiveFun5(int n)
{
    for (i = 0; i < n; i += 2) {
        // do something
    }

    if (n <= 0)
        return 1;
    else
        return 1 + recursiveFun5(n-5);
}

And here the for loop takes n/2 since we're increasing by 2, and the recursion takes n/5 and since the for loop is called recursively, therefore, the time complexity is in

(n/5) * (n/2) = n^2/10,

due to Asymptotic behavior and worst-case scenario considerations or the upper bound that big O is striving for, we are only interested in the largest term so O(n^2).


Good luck on your midterms ;)

How to get the last value of an ArrayList

If you use a LinkedList instead , you can access the first element and the last one with just getFirst() and getLast() (if you want a cleaner way than size() -1 and get(0))

Implementation

Declare a LinkedList

LinkedList<Object> mLinkedList = new LinkedList<>();

Then this are the methods you can use to get what you want, in this case we are talking about FIRST and LAST element of a list

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

So , then you can use

mLinkedList.getLast(); 

to get the last element of the list.

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

Get my phone number in android

private String getMyPhoneNumber(){
    TelephonyManager mTelephonyMgr;
    mTelephonyMgr = (TelephonyManager)
        getSystemService(Context.TELEPHONY_SERVICE); 
    return mTelephonyMgr.getLine1Number();
}

private String getMy10DigitPhoneNumber(){
    String s = getMyPhoneNumber();
    return s.substring(2);
}

Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

<table>
    <tr>
        <td colspan = "2">
            <!-- Merged Columns -->
        </td>
    </tr>

    <tr>
        <td>
            <!-- Column 1 -->
        </td>

        <td>
            <!-- Column 2 -->
        </td>
    </tr>
</table>

See also
     W3 official docs on HTML Tables

How to write a JSON file in C#?

The example in Liam's answer saves the file as string in a single line. I prefer to add formatting. Someone in the future may want to change some value manually in the file. If you add formatting it's easier to do so.

The following adds basic JSON indentation:

 string json = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

How to find list intersection?

If, by Boolean AND, you mean items that appear in both lists, e.g. intersection, then you should look at Python's set and frozenset types.

How to convert seconds to time format?

If you were to hardcode it you would use modulus to extract the time as others suggested.

If you are returning the seconds from MySQL database, assuming you don't need the data in seconds format in your app, there is a much cleaner way to do it, you can use MySQL's SEC_TO_TIME and it will return time in hh:mm:ss format.

Eg.

SELECT SEC_TO_TIME(my_seconds_field) AS my_timestring;

How to export a MySQL database to JSON?

Also, If you are exporting in application layer don't forget to limit results. For example if you've 10M rows, you should get results part by part.

How to get selected value of a dropdown menu in ReactJS

Just use onChange event of the <select> object. Selected value is in e.target.value then.

By the way, it's a bad practice to use id="...". It's better to use ref=">.." http://facebook.github.io/react/docs/more-about-refs.html

creating batch script to unzip a file without additional zip tools

Here is a quick and simple solution using PowerShell:

powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere answers all questions with yes.

Style input element to fill remaining width of its container

Very easy trick is using a CSS calc formula. All modern browsers, IE9, wide range of mobile browsers should support this.

<div style='white-space:nowrap'>
  <span style='display:inline-block;width:80px;font-weight:bold'>
    <label for='field1'>Field1</label>
  </span>
  <input id='field1' name='field1' type='text' value='Some text' size='30' style='width:calc(100% - 80px)' />
</div>

Textarea Auto height

I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.

Get clicked item and its position in RecyclerView

//Create below methods into the Activity which contains RecyclerView.


private void createRecyclerView() {

final RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    MyAdapter myAdapter=new MyAdapter(dataAray,MianActivity.this);
    recyclerView.setAdapter(myAdapter);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    setRecyclerViewClickListner(recyclerView);
}

private void setRecyclerViewClickListner(RecyclerView recyclerView){

    final GestureDetector gestureDetector = new GestureDetector(MainActivity.this,new GestureDetector.SimpleOnGestureListener() {
        @Override public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });


    recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child =recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
            if(child!=null && gestureDetector.onTouchEvent(motionEvent)){
               int position=recyclerView.getChildLayoutPosition(child);
                String name=itemArray.get(position).name;

            return true;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean b) {

        }
    });
}

How to combine two byte arrays

String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
    byteData[start + i] = byteSalt[i];
}

The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:

for (int i = 0; i < byteData.length; i ++)

with:

for (int i = 0; i < byteSalt.length; i ++)

What is the difference between float and double?

Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.

How can I get the length of text entered in a textbox using jQuery?

var myLength = $("#myTextbox").val().length;

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Take a look at the JSONObject reference:

http://www.json.org/javadoc/org/json/JSONObject.html

Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.

How do you use MySQL's source command to import large files in windows

Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this

D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql

Option 1 for wampp

D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql

change your folder and mysql version

Option 2 Suppose your current path is which is showing command prompt

C:\Users\shafiq;

then change directory using cd.. then goto your mysql directory where your xampp installed. Then cd.. for change directory. then go to bin folder.

C:\xampp\mysql\bin;

C:\xampp\mysql\bin\mysql -u {username} -p {database password}.then please enter when you see enter password in command prompt.

choose database using

mysql->use test (where database name test) 

then put in source sql in bin folder.

then last command will be

mysql-> source test.sql (where test.sql is file name which need to import)

then press enter

This is full command

C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
 mysql-> use test
 mysql->source test.sql