Programs & Examples On #Uiq3

How do I define the name of image built with docker-compose

According to 3.9 version of Docker compose, you can use image: myapp:tag to specify name and tag.

version: "3.9"
services:
  webapp:
    build:
      context: .
      dockerfile: Dockerfile
    image: webapp:tag

Reference: https://docs.docker.com/compose/compose-file/compose-file-v3/

Android Studio AVD - Emulator: Process finished with exit code 1

I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.

In android studio ,

Help Menu -> Show log in explorer.

It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"

  1. Try to run emulator from command prompt ,
  • Go to folder ~\Android\Sdk\emulator

  • Run this command:

    emulator.exe -netdelay none -netspeed full -avd <virtual device name> 
    
    ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
    

    You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt

  1. If you get error about vcruntime140 ,
  • Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator

  • Try step 1

  • If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1

  1. If you get error about msvcp140.dll
  • Search and download the appropriate msvcp140.dll file for your system from the internet (32 / 64 bit version)
  • Replace the file in the folder C:\Windows\System32 with file msvcp140.dll
  • Try step 1

If it runs , you can run it from Android Studio also.

Pandas: sum DataFrame rows for given columns

Create a list of column names you want to add up.

df['total']=df.loc[:,list_name].sum(axis=1)

If you want the sum for certain rows, specify the rows using ':'

Replacing H1 text with a logo image: best method for SEO and accessibility?

I don't know but this is the format have used...

<h1>
    <span id="site-logo" title="xxx" href="#" target="_self">
        <img src="http://www.xxx.com/images/xxx.png" alt="xxx" width="xxx" height="xxx" />
        <a style="display:none">
            <strong>xxx</strong>
        </a>
    </span>
</h1>

Simple and it has not done my site any harm as far as I can see. You could css it but I don't see it loading any faster.

"Input string was not in a correct format."

It looks like some space include in the text. Use

lvTwoOrMoreOptions.SelectedItems[0].Text.ToString().Trim()

and convert to int32.

hope this code will solve you

From comments

if your ListView is in report mode (i.e. it looks like a grid) then you will need the SubItems property. lvTwoOrMoreOptions.SelectedItems gets you each items in the list view - SubItems gets you the columns. So lvTwoOrMoreOptions.SelectedItems[0].SubItems[0] is the first column value,

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

Converting to upper and lower case in Java

/* This code is just for convert a single uppercase character to lowercase 
character & vice versa.................*/

/* This code is made without java library function, and also uses run time input...*/



import java.util.Scanner;

class CaseConvert {
char c;
void input(){
//@SuppressWarnings("resource")  //only eclipse users..
Scanner in =new Scanner(System.in);  //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0);     // input a single character
}
void convert(){
if(c>=65 && c<=90){
    c=(char) (c+32);
    System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
        c=(char) (c-32);
        System.out.print("Converted to Uppercase :"+c);
}
else
    System.out.println("invalid Character Entered  :" +c);

}


  public static void main(String[] args) {
    // TODO Auto-generated method stub
    CaseConvert obj=new CaseConvert();
    obj.input();
    obj.convert();
    }

}



/*OUTPUT..Enter Any Character :A Converted to Lowercase :a 
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered  :+*/

Error: Cannot find module 'webpack'

Just found out that using Atom IDE terminal did not install dependencies locally (probably a bug or just me). Installing git bash externally and running npm commands again worked for me

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Cannot find "Package Explorer" view in Eclipse

Try Window > Open Perspective > Java Browsing or some other Java perspectives

How do I compile a Visual Studio project from the command-line?

MSBuild usually works, but I've run into difficulties before. You may have better luck with

devenv YourSolution.sln /Build 

Read response headers from API response - Angular 5 + TypeScript

In my case in the POST response I want to have the authorization header because I was having the JWT Token in it. So what I read from this post is the header I we want should be added as an Expose Header from the back-end. So what I did was added the Authorization header to my Exposed Header like this in my filter class.

response.addHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Custom-header");
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); // HEADER_STRING == Authorization

And at my Angular Side

In the Component.

this.authenticationService.login(this.f.email.value, this.f.password.value)
  .pipe(first())
  .subscribe(
    (data: HttpResponse<any>) => {
      console.log(data.headers.get('authorization'));
    },
    error => {
      this.loading = false;
    });

At my Service Side.

return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password},
  {observe: 'response' as 'body'})
  .pipe(map(user => {
       return user;
  }));

On Duplicate Key Update same as insert

There is no other way, I have to specify everything twice. First for the insert, second in the update case.

Format Instant to String

The Instant class doesn't contain Zone information, it only stores timestamp in milliseconds from UNIX epoch, i.e. 1 Jan 1070 from UTC. So, formatter can't print a date because date always printed for concrete time zone. You should set time zone to formatter and all will be fine, like this :

Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

Most simple code to populate JTable from ResultSet

You have to Download the Jar called rs2xml by click this link rs2xml.jar Then Add it to your project libraries then import

import net.proteanit.sql.DbUtils;

I prepare Only a method to do so as a sample

private void Update_table(){
    try{
        // fetch a connection
        connection = your_connection_class_name_here.getInstance().getConnection();
        if (connection != null) {
        String sql="select name,description  from sell_mode";
        pst=connection.prepareStatement(sql);
        rs=pst.executeQuery();
         your_table_name_for_populating_your_Data.setModel(DbUtils.resultSetToTableModel(rs));
        }
    }
    catch(IOException | SQLException | PropertyVetoException e){
    JOptionPane.showMessageDialog(null,e);
    }
    finally {
          if (rs!= null) try { rs.close(); } catch (SQLException e) {}
          if (pst != null) try { pst.close(); } catch (SQLException e) {}
          if (connection != null) try { connection.close(); } catch (SQLException e) {}
      }
}

Hope this will help more

Use jQuery to hide a DIV when the user clicks outside of it

Toggle for regular and touch devices

I read some answers here a while back and created some code I use for div's that function as popup bubbles.

$('#openPopupBubble').click(function(){
    $('#popupBubble').toggle();

    if($('#popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$('#popupBubble').find('*').is(e.target)){
                $('#popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

You can also make this more abstract using classes and select the correct popup bubble based on the button that triggered the click event.

$('body').on('click', '.openPopupBubble', function(){
    $(this).next('.popupBubble').toggle();

    if($(this).next('.popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($(this).is(e.target) || $(this).find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$(this).next('.popupBubble').find('*').is(e.target)){
                $(this).next('.popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2019 (Express Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQL2019\Express_ENU and click OK

Combine several images horizontally with Python

You can do something like this:

import sys
from PIL import Image

images = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
widths, heights = zip(*(i.size for i in images))

total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

x_offset = 0
for im in images:
  new_im.paste(im, (x_offset,0))
  x_offset += im.size[0]

new_im.save('test.jpg')

Test1.jpg

Test1.jpg

Test2.jpg

Test2.jpg

Test3.jpg

Test3.jpg

test.jpg

enter image description here


The nested for for i in xrange(0,444,95): is pasting each image 5 times, staggered 95 pixels apart. Each outer loop iteration pasting over the previous.

for elem in list_im:
  for i in xrange(0,444,95):
    im=Image.open(elem)
    new_im.paste(im, (i,0))
  new_im.save('new_' + elem + '.jpg')

enter image description here enter image description here enter image description here

Hiding the address bar of a browser (popup)

Its not possible to hide address bar of browser.

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

Need to get current timestamp in Java

The threadunsafety of SimpleDateFormat should not be an issue if you just create it inside the very same method block as you use it. In other words, you are not assigning it as static or instance variable of a class and reusing it in one or more methods which can be invoked by multiple threads. Only this way the threadunsafety of SimpleDateFormat will be exposed. You can however safely reuse the same SimpleDateFormat instance within the very same method block as it would be accessed by the current thread only.

Also, the java.sql.Timestamp class which you're using there should not be abused as it's specific to the JDBC API in order to be able to store or retrieve a TIMESTAMP/DATETIME column type in a SQL database and convert it from/to java.util.Date.

So, this should do:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 12/01/2011 4:48:16 PM

ORA-12560: TNS:protocol adaptor error

It really has worked on my machine. But instead of OracleServiceORCL I found OracleServiceXE.

How do you run a Python script as a service in Windows?

nssm in python 3+

(I converted my .py file to .exe with pyinstaller)

nssm: as said before

  • run nssm install {ServiceName}
  • On NSSM´s console:

    path: path\to\your\program.exe

    Startup directory: path\to\your\ #same as the path but without your program.exe

    Arguments: empty

If you don't want to convert your project to .exe

  • create a .bat file with python {{your python.py file name}}
  • and set the path to the .bat file

Is there a Python Library that contains a list of all the ascii characters?

Since ASCII printable characters are a pretty small list (bytes with values between 32 and 127), it's easy enough to generate when you need:

>>> for c in (chr(i) for i in range(32,127)):
...     print c
... 

!
"
#
$
%
... # a few lines removed :)
y
z
{
|
}
~

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

WORDPRESS is having this error mostly:
SOLUTION:
Locate your PHP installed directory on Remote live hosting SERVER or "Local Server"
In case of Windows os
for example if you using xampp or wamp webserver. it will be in xammp directory 'c:\xammp\php'
Note: For Unix/Linux OS, locate your PHP directory in Webserver

Find & Edit PHP.INI file
Find 'allow_url_include'
replace it with value 'on'
allow_url_include=On
Save you php.ini & RESTART you web-server.

Is it possible to modify a string of char in C?

You could also use strdup:

   The strdup() function returns a pointer to a new string which is a duplicate of the string  s.
   Memory for the new string is obtained with malloc(3), and can be freed with free(3).

For you example:

char *a = strdup("stack overflow");

Best way to load module/class from lib folder in Rails 3?

Spell the filename correctly.

Seriously. I battled with a class for an hour because the class was Governance::ArchitectureBoard and the file was in lib/governance/architecture_baord.rb (transposed O and A in "board")

Seems obvious in retrospect, but it was the devil tracking that down. If the class is not defined in the file that Rails expects it to be in based on munging the class name, it is simply not going to find it.

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had the same problem with a different and simple solution.

Problem

I installed PHP 5.6 following the accepted answer to this question on Ask Ubuntu. After using Virtualmin to switch a particular virtual server from PHP 5.5 to PHP 5.6, I received a 500 Internal Server Error and had the same entries in the apache error log:

[Tue Jul 03 16:15:22.131051 2018] [fcgid:warn] [pid 24262] (104)Connection reset by peer: [client 10.20.30.40:23700] mod_fcgid: error reading data from FastCGI server
[Tue Jul 03 16:15:22.131101 2018] [core:error] [pid 24262] [client 10.20.30.40:23700] End of script output before headers: index.php

Cause

Simple: I didn't install the php5.6-cgi packet.

Fix

Installing the packet and reloading apache solved the problem:

  • sudo apt-get install php5.6-cgi if you are using PHP 5.6

  • sudo apt-get install php5-cgi if you are using a different PHP 5 version

  • sudo apt-get install php7.0-cgi if you are using PHP 7

Then use service apache2 reload to apply the configuration.

Cross-browser window resize event - JavaScript / jQuery

Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:

function foo(){....};
window.onresize=foo;

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE This view is invisible, and it doesn't take any space for layout purposes.

View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

How to get IP address of the device from code?

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString();

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

httpd-xampp.conf: How to allow access to an external IP besides localhost?

<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from all
Allow from ::1 127.0.0.0/8 
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var

add to txt file > httpd-xampp.conf

Is it possible to use raw SQL within a Spring Repository

we can use createNativeQuery("Here Nagitive SQL Query ");

for Example :

Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();

Validating a Textbox field for only numeric input.

Use Regex as below.

if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
 MessageBox.show("add content");
} else {
 MessageBox.show("add content");
}

jQuery - setting the selected value of a select control via its text description

I haven't tested this, but this might work for you.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

Why is there no tuple comprehension in Python?

My best guess is that they ran out of brackets and didn't think it would be useful enough to warrent adding an "ugly" syntax ...

better way to drop nan rows in pandas

Use dropna:

dat.dropna()

You can pass param how to drop if all labels are nan or any of the labels are nan

dat.dropna(how='any')    #to drop if any value in the row has a nan
dat.dropna(how='all')    #to drop if all values in the row are nan

Hope that answers your question!

Edit 1: In case you want to drop rows containing nan values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:

dat.dropna(subset=[col_list])  # col_list is a list of column names to consider for nan values.

How can I see CakePHP's SQL dump in the controller?

What worked finally for me and also compatible with 2.0 is to add in my layout (or in model)

<?php echo $this->element('sql_dump');?>

It is also depending on debug variable setted into Config/core.php

How to select last two characters of a string

You should use substring, not jQuery, to do this.

Try something like this:

member.substring(member.length - 2, member.length)

W3Schools (not official, but occasionally helpful): http://www.w3schools.com/jsref/jsref_substring.asp

Adding MDN link as requested by commenter: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substring

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

How can I make the computer beep in C#?

In .Net 2.0, you can use Console.Beep().

// Default beep
Console.Beep();

You can also specify the frequency and length of the beep in milliseconds.

// Beep at 5000 Hz for 1 second
Console.Beep(5000, 1000);

For more information refer http://msdn.microsoft.com/en-us/library/8hftfeyw%28v=vs.110%29.aspx

Display Yes and No buttons instead of OK and Cancel in Confirm box?

As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though

Styling a input type=number

I modified @LcSalazar's answer a bit... it's still not perfect because the background of the default buttons can still be seen in both Firefox, Chrome & Opera (not tested in Safari); but clicking on the arrows still works

Notes:

  • Adding pointer-events: none; allows you to click through the overlapping button, but then you can not style the button while hovered.
  • The arrows are visible in Edge, but don't work because Edge doesn't use arrows. It only adds an "x" to clear the input.

_x000D_
_x000D_
.number-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:after,_x000D_
.number-wrapper:before {_x000D_
  position: absolute;_x000D_
  right: 5px;_x000D_
  width: 1.6em;_x000D_
  height: .9em;_x000D_
  font-size: 10px;_x000D_
  pointer-events: none;_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
.number-wrapper:after {_x000D_
  color: blue;_x000D_
  content: "\25B2";_x000D_
  margin-top: 1px;_x000D_
}_x000D_
_x000D_
.number-wrapper:before {_x000D_
  color: red;_x000D_
  content: "\25BC";_x000D_
  margin-bottom: 5px;_x000D_
  bottom: -.5em;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

ipad safari: disable scrolling, and bounce effect?

You can use this jQuery code snippet to do this:

$(document).bind(
      'touchmove',
          function(e) {
            e.preventDefault();
          }
);

This will block the vertical scrolling and also any bounce back effect occurring on your pages.

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

Make a td fixed size (width,height) while rest of td's can expand

This will take care of the empty td:

<td style="min-width: 20px;"></td>

How do I write a RGB color value in JavaScript?

I am showing with an example of adding random color. You can write this way

var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var col = "rgb(" + r + "," + g + "," + b + ")";
parent.childNodes[1].style.color = col;

The property is expected as a string

Returning from a void function

Neither is more correct, so take your pick. The empty return; statement is provided to allow a return in a void function from somewhere other than the end. No other reason I believe.

How to access a value defined in the application.properties file in Spring Boot

You can do it this way as well....

@Component
@PropertySource("classpath:application.properties")
public class ConfigProperties {

    @Autowired
    private Environment env;

    public String getConfigValue(String configKey){
        return env.getProperty(configKey);
    }
}

Then wherever you want to read from application.properties, just pass the key to getConfigValue method.

@Autowired
ConfigProperties configProp;

// Read server.port from app.prop
String portNumber = configProp.getConfigValue("server.port"); 

Getting JSONObject from JSONArray

Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

In SQL Server, what does "SET ANSI_NULLS ON" mean?

Set ANSI NULLS OFF will make NULL = NULL comparision return true. EG :

        SET ANSI_NULLS OFF
        select * from sys.tables
        where principal_id = Null

will return some result as displayed below: zcwInvoiceDeliveryType 744547 NULL zcExpenseRptStatusTrack 2099048 NULL ZCVendorPermissions 2840564 NULL ZCWOrgLevelClientFee 4322525 NULL

While this query will not return any results:

        SET ANSI_NULLS ON 
        select * from sys.tables
        where principal_id = Null

Clear terminal in Python

You could tear through the terminfo database, but the functions for doing so are in curses anyway.

What is the use of static constructors?

No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.

It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

How to leave/exit/deactivate a Python virtualenv

It is very simple, in order to deactivate your virtual env

  • If using Anaconda - use conda deactivate
  • If not using Anaconda - use source deactivate

Populating a data frame in R in a loop

It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:

  1. Preallocate your data.frame. This is not recommended because indexing is slow for data.frames.
  2. Use another data structure in the loop and transform into a data.frame afterwards. A list is very useful here.

Example to illustrate the general approach:

mylist <- list() #create an empty list

for (i in 1:5) {
  vec <- numeric(5) #preallocate a numeric vector
  for (j in 1:5) { #fill the vector
    vec[j] <- i^j 
  }
  mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix

In this example it is not necessary to use a list, you could preallocate a matrix. However, if you do not know how many iterations your loop will need, you should use a list.

Finally here is a vectorized alternative to the example loop:

outer(1:5,1:5,function(i,j) i^j)

As you see it's simpler and also more efficient.

#1071 - Specified key was too long; max key length is 767 bytes

Here is my original answer:

I just drop database and recreate like this, and the error is gone:

drop database if exists rhodes; create database rhodes default CHARACTER set utf8 default COLLATE utf8_general_ci;

However, it doesn't work for all the cases.

It is actually a problem of using indexes on VARCHAR columns with the character set utf8 (or utf8mb4), with VARCHAR columns that have more than a certain length of characters. In the case of utf8mb4, that certain length is 191.

Please refer to the Long Index section in this article for more information how to use long indexes in MySQL database: http://hanoian.com/content/index.php/24-automate-the-converting-a-mysql-database-character-set-to-utf8mb4

configure: error: C compiler cannot create executables

For me it was a problem with gcc, highlighted by gcc -v. It was down to upgrading Xcode recently this post said to do sudo xcode-select -switch /Applications/Xcode.app which fixed the issue.

Input type "number" won't resize

Seem like the input type number does not support size attribute or it's not compatible along browsers, you can set it through CSS instead:

input[type=number]{
    width: 80px;
} 

Updated Fiddle

The project description file (.project) for my project is missing

If you only want to checkout and you delete the folder from the workspace you also need to delete the reference to it in the Java view. Then it should checkout as if it were checking out for the first time.

How Exactly Does @param Work - Java

@param won't affect the number. It's just for making javadocs.

More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

cast or convert a float to nvarchar?

Check STR. You need something like SELECT STR([Column_Name],10,0) ** This is SQL Server solution, for other servers check their docs.

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Cannot connect to Database server (mysql workbench)

Run the ALTER USER command. Be sure to change password to a strong password of your choosing.

  1. sudo mysql # Login to mysql`

  2. Run the below command

    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
    

Now you can access it by using the new password.

Ref : https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I'm using Mojave with rbenv, this solution works for me:

$ vi ~/.bash_profile

Add this line into the file:

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

How do I make a placeholder for a 'select' box?

Here's my contribution. Haml + CoffeeScript + SCSS

Haml

=f.collection_select :country_id, [us] + Country.all, :id, :name, {prompt: t('user.country')}, class: 'form-control'

CoffeeScript

  $('select').on 'change', ->
    if $(this).val()
      $(this).css('color', 'black')
    else
      $(this).css('color', 'gray')
  $('select').change()

SCSS

select option {
  color: black;
}

It's possible to use only CSS by changing the server code and only setting the class styles depending on the current value of the property, but this way seems easier and cleaner.

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  if ($(this).val()) {_x000D_
    return $(this).css('color', 'black');_x000D_
  } else {_x000D_
    return $(this).css('color', 'gray');_x000D_
  }_x000D_
});_x000D_
_x000D_
$('select').change();
_x000D_
    select option {_x000D_
      color: black;_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select class="form-control" name="user[country_id]" id="user_country_id">_x000D_
  <option value="">Country</option>_x000D_
                      <option value="231">United States</option>_x000D_
                      <option value="1">Andorra</option>_x000D_
                      <option value="2">Afghanistan</option>_x000D_
                      <option value="248">Zimbabwe</option></select>
_x000D_
_x000D_
_x000D_

You can add more CSS (select option:first-child) to keep the placeholder gray when it opens, but I didn't care about that.

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

Your question "what are they" is already answered above.

As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:

_isnan(), _isfinite(), and _fpclass()

On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).

javascript create empty array of a given size

In 2018 and thenceforth we shall use [...Array(500)] to that end.

How to Write text file Java

I would like to add a bit more to MadProgrammer's Answer.

In case of multiple line writing, when executing the command

writer.write(string);

one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,

System.out.println("\n");

Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using

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

and then using the newline variable instead of "\n". This will get the output in the way you want it.

RegEx pattern any two letters followed by six numbers

Depending on if your regex flavor supports it, I might use:

\b[A-Z]{2}\d{6}\b    # Ensure there are "word boundaries" on either side, or

(?<![A-Z])[A-Z]{2}\d{6}(?!\d) # Ensure there isn't a uppercase letter before
                              # and that there is not a digit after

IntelliJ: Error:java: error: release version 5 not supported

You should do one more change by either below approaches:


1 Through IntelliJ GUI

As mentioned by 'tataelm':

Project Structure > Project Settings > Modules > Language level: > then change to your preferred language level


2 Edit IntelliJ config file directly

Open the <ProjectName>.iml file (it is created automatically in your project folder if you're using IntelliJ) directly by editing the following line,

From: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">

To: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_11">

As your approach is also meaning to edit this file. :)


Approach 1 is actually asking IntelliJ to help edit the .iml file instead of doing by you directly.

How do I get an animated gif to work in WPF?

Adding on to the main response that recommends the usage of WpfAnimatedGif, you must add the following lines in the end if you are swapping an image with a Gif to ensure the animation actually executes:

ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);

So your code will look like:

var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));
ImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

Empty set literal?

There are few ways to create empty Set in Python :

  1. Using set() method
    This is the built-in method in python that creates Empty set in that variable.
  2. Using clear() method (creative Engineer Technique LOL)
    See this Example:

    sets={"Hi","How","are","You","All"}
    type(sets)  (This Line Output : set)
    sets.clear()
    print(sets)  (This Line Output : {})
    type(sets)  (This Line Output : set)

So, This are 2 ways to create empty Set.

android TextView: setting the background color dynamically doesn't work

Here are the steps to do it correctly:

  1. First of all, declare an instance of TextView in your MainActivity.java as follows:

    TextView mTextView;
    
  2. Set some text DYNAMICALLY(if you want) as follows:

    mTextView.setText("some_text");
    
  3. Now, to set the background color, you need to define your own color in the res->values->colors.xml file as follows:

    <resources>
        <color name="my_color">#000000</color>
    </resources>
    
  4. You can now use "my_color" color in your java file to set the background dynamically as follows:

    mTextView.setBackgroundResource(R.color.my_color);
    

Django templates: If false?

You could write a custom template filter to do this in a half-dozen lines of code:

from django.template import Library

register = Library()

@register.filter
def is_false(arg): 
    return arg is False

Then in your template:

{% if myvar|is_false %}...{% endif %}

Of course, you could make that template tag much more generic... but this suits your needs specifically ;-)

jQuery .val change doesn't change input value

Use attr instead.
$('#link').attr('value', 'new value');

demo

Try-catch block in Jenkins pipeline script

Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        }
        ...continue with other code...
}

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

C++ templates that accept only certain types

I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:

template<typename T>
class ObservableList {
    BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
    ...
};

In some other, simpler cases, you can simply forward-declare a global template, but only define (explicitly or partially specialise) it for the valid types:

template<typename T> class my_template;     // Declare, but don't define

// int is a valid type
template<> class my_template<int> {
    ...
};

// All pointer types are valid
template<typename T> class my_template<T*> {
    ...
};

// All other types are invalid, and will cause linker error messages.

[Minor EDIT 6/12/2013: Using a declared-but-not-defined template will result in linker, not compiler, error messages.]

What's the best UI for entering date of birth?

If your goal is to make sure "the user won't be confused at all," I think this is the best option.

three dropdowns for month, day, year

I wouldn't recommend a datepicker for date of birth. First you have to browse to the year (click, click, click…), then to the month (click some more), and then find and click the tiny number on a grid.

Datepickers are useful when you don't know the exact date off the top of your head, e.g. you're planning a trip for the second week of February.

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

Looking for simple Java in-memory cache

You can easily use imcache. A sample code is below.

void example(){
    Cache<Integer,Integer> cache = CacheBuilder.heapCache().
    cacheLoader(new CacheLoader<Integer, Integer>() {
        public Integer load(Integer key) {
            return null;
        }
    }).capacity(10000).build(); 
}

why I can't get value of label with jquery and javascript?

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

What is Gradle in Android Studio?

Short and simple answer for that,

Gradle is a build system, which is responsible for code compilation, testing, deployment and conversion of the code into . dex files and hence running the app on the device. As Android Studio comes with Gradle system pre-installed, there is no need to install additional runtime softwares to build our project.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

Solution:

Dowload the ultimate version of Gradle

http://services.gradle.org/distributions/

gradle-4.x-rc-1-all.zip.sha256 09-Jan-2018 01:15 +0000 64.00B

Unzip the distribution

Go to Android Studio -> File -> Settings -> Gradle -> Use local gradle distribution Search the file and OK

In the gradle:app write this, implementation(path: ':animators', configuration: 'default')

dependencies {
   .
   .
   .


    implementation project(path: ':animators', configuration: 'default')


}

How to get the new value of an HTML input after a keypress has modified it?

There are two kinds of input value: field's property and field's html attribute.

If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).

How to see JavaDoc in IntelliJ IDEA?

To best mirror Eclipses functionality, enable the following settings:

  • IDE Settings/Editor -> Other.Show quick doc on mouse move
  • IDE Settings/Editor/Code Completion -> Autopopup Documentation

To see the javadoc in the autocomplete menu, hit '.' to get the popup, then hover over the object you are working with, once you get the javadoc popup, you can select an item in the popup to switch the javadoc over. Not ideal... But its something.

As another note. The search functionality of the options menu is very useful. Just type in 'doc' and you will see all the options for doc.

Also, searching for "autopopup doc" will not only find each of the options, but it will also highlight them in the menu. Pretty awesome!


Edit: Going beyond the initial question, this might be useful for people who just want quick and easy access to the docs.

After using this for a few more days, it seems just getting used to using the hotkey is the most efficient way. It will pop up the documentation for anything at the spot of where your text input marker is so you never have to touch the mouse. This works in the intellisense popup as well and will stay up while navigating up and down.

Personally, Ctrl+Q on windows was not ideal so I remapped it to Alt+D. Remaping can be done under IDE Settings/Keymap. Once in the keymap menu, just search for Quick Documentation.

How to specify line breaks in a multi-line flexbox layout?

I tried several answers here, and none of them worked. Ironically, what did work was about the simplest alternative to a <br/> one could attempt:

<div style="flex-basis: 100%;"></div>

or you could also do:

<div style="width: 100%;"></div>

Place that wherever you want a new line. It seems to work even with adjacent <span>'s, but I'm using it with adjacent <div>'s.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

Change this key in the Info.plist

I changed from

<key>JVMVersion</key>
<string>1.6*</string>

to

<key>JVMVersion</key>
<string>1.8*</string>

and it worked fine now..

Edited:
Per the official statement as mentioned above by hasternet and aried3r, the solution by Antonio Jose is correct.

Thanks!

How can I check if a Perl array contains a particular value?

You certainly want a hash here. Place the bad parameters as keys in the hash, then decide whether a particular parameter exists in the hash.

our %bad_params = map { $_ => 1 } qw(badparam1 badparam2 badparam3)

if ($bad_params{$new_param}) {
  print "That is a bad parameter\n";
}

If you are really interested in doing it with an array, look at List::Util or List::MoreUtils

Is there an equivalent method to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

Java compiler level does not match the version of the installed Java project facet

I changed the configuration inside workspace/project/.setting/org.eclipse.wst.common.project.facet.core to :

installed facet="jst.web" version="2.5"
installed facet="jst.java" version="1.7"

Before changing config, remove project from IDE. This worked for me.

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

PHP Configuration: It is not safe to rely on the system's timezone settings

Tchalvak, who commented on the original question, hit the nail on the head for me. I've been editing (I use Debian):

/etc/php5/apache2/php.ini

...which had the correct timezone for me and was the only .ini file being loaded with date.timezone within it, but I was receiving the above error when I ran a script through Bash. I had no idea that I should have been editing:

/etc/php5/cli/php.ini

as well. (Well, for me it was 'as well', for you it might be different of course, but I'm going to keep my Apache and CLI versions of php.ini synchronised now).

How to call a PHP file from HTML or Javascript

You just need to post the form data to the insert php file function, see below :)

class DbConnect
{
// Database login vars
private $dbHostname = '';
private $dbDatabase = '';
private $dbUsername = '';
private $dbPassword = '';
public $db = null;

public function connect()
{

    try
    {
        $this->db = new PDO("mysql:host=".$this->dbHostname.";dbname=".$this->dbDatabase, $this->dbUsername, $this->dbPassword);
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
        echo "It seems there was an error.  Please refresh your browser and try again. ".$e->getMessage();
    }
}

public function store($email)
{
    $stm = $this->db->prepare('INSERT INTO subscribers (email) VALUES ?');
    $stm->bindValue(1, $email);

    return $stm->execute();
}
}

Read all worksheets in an Excel workbook into an R list with data.frames

excel.link will do the job.

I actually found it easier to use compared to XLConnect (not that either package is that difficult to use). Learning curve for both was about 5 minutes.

As an aside, you can easily find all R packages that mention the word "Excel" by browsing to http://cran.r-project.org/web/packages/available_packages_by_name.html

Javascript to stop HTML5 video playback on modal window close

For anyone struggling with this issue with videos embedded using the <object> tag, the function you want is Quicktime's element.Stop(); For example, to stop any and all playing movies, use:

var videos = $("object");

for (var i=0; i < videos.length; i++)
{
    if (videos[i].Stop) { videos[i].Stop(); }
}

Note the non-standard capital "S" on Stop();

The request failed or the service did not respond in a timely fashion?

I found from event logs that My SQL server evaluation has expired. I needed to upgrade or needed to use community edition.

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

here is one very simple example:

ASPX:

<asp:GridView ID="gvTest" runat="server" SelectedRowStyle-BackColor="#996633" 
       SelectedRowStyle-ForeColor="Fuchsia">
    <Columns>
        <asp:CommandField ShowSelectButton="True" />
        <asp:TemplateField>
            <ItemTemplate>
                <%# Container.DataItemIndex + 1 %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdateClick"/>

Code Behind:

public partial class _Default : System.Web.UI.Page
{
    private readonly DataTable _dataTable;

    public _Default()
    {
        _dataTable = new DataTable();

        _dataTable.Columns.Add("Serial", typeof (int));
        _dataTable.Columns.Add("Data", typeof (string));

        for (var i = 0; ++i <= 15;) 
        _dataTable.Rows.Add(new object[] {i, "This is row " + i});
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindData();
    }

    private void BindData()
    {
        gvTest.DataSource = _dataTable;
        gvTest.DataBind();
    }

    protected void btnUpdateClick(object sender, EventArgs e)
    {
        if (gvTest.SelectedIndex < 0) return;

        var r = gvTest.SelectedRow;

        var i = r.DataItemIndex;

        //you can get primary key or anyother column vlaue by 
        //accessing r.Cells collection, but for this simple case
        //we will use index of selected row in database.
        _dataTable.Rows.RemoveAt(i);

        //rebind with data
        BindData();

        //clear selection from grid
        gvTest.SelectedIndex = -1;
    }
}

you will have to use checkboxes or some other mechanism to allow users to select multiple rows and then you can browse the rows for ones with the checkbox checked and then remove those rows.

Given URL is not allowed by the Application configuration Facebook application error

You need to add the URL to your app:

  1. Go to the app, you want for user login, on the Facebook Developers page
  2. Click on the settings tab
  3. Click add platform
  4. Select Website
  5. After selection it will ask for some details such as URL for your website which uses login with facebook feature, fill the form and submit it

That's all and you are done. Make sure that the app's URL is the same from where you're logging in.

Custom Python list sorting

Just like this example. You want sort this list.

[('c', 2), ('b', 2), ('a', 3)]

output:

[('a', 3), ('b', 2), ('c', 2)]

you should sort the tuples by the second item, then the first:

def letter_cmp(a, b):
    if a[1] > b[1]:
        return -1
    elif a[1] == b[1]:
        if a[0] > b[0]:
            return 1
        else:
            return -1
    else:
        return 1

Then convert it to a key function:

from functools import cmp_to_key
letter_cmp_key = cmp_to_key(letter_cmp))

Now you can use your custom sort order:

[('c', 2), ('b', 2), ('a', 3)].sort(key=letter_cmp_key)

How to hide Bootstrap modal with javascript?

I use Bootstrap 3.4 For me this does not work

$('#myModal').modal('hide')

In desperation,I did this:

$('#myModal').hide();
$('.modal-backdrop').hide();

Maybe it's not elegant, but it works

MySQL: How to reset or change the MySQL root password?

I am sharing the step by step final solution to reset a MySQL password in Linux Ubuntu.

Reference taken from blog (dbrnd.com)

Step 1: Stop MySQL Service.

sudo stop mysql

Step 2: Kill all running mysqld.

sudo killall -9 mysqld

Step 3: Starting mysqld in Safe mode.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Step 4: Start mysql client

mysql -u root

Step 5: After successful login, please execute this command to change any password.

FLUSH PRIVILEGES;

Step 6: You can update mysql root password .

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Note: On MySQL 5.7, column Password is called authentication_string.

Step 7: Please execute this command.

FLUSH PRIVILEGES;

fatal: The current branch master has no upstream branch

If you are on any branch, you can use this:

git push origin head -u

This will automatically create new branch of the same name on the remote.

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

How to var_dump variables in twig templates?

The complete recipe here for quicker reference (note that all the steps are mandatory):

1) when instantiating Twig, pass the debug option

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2) add the debug extension

$twig->addExtension(new \Twig_Extension_Debug());

3) Use it like @Hazarapet Tunanyan pointed out

{{ dump(MyVar) }}

or

{{ dump() }}

or

{{ dump(MyObject.MyPropertyName) }}

Specifying width and height as percentages without skewing photo proportions in HTML

You can set one or the other (just not both) and that should get the result you want.

<img src="#" height="50%">

how to change color of TextinputLayout's label and edittext underline android

I used all of the above answers and none worked. This answer works for API 21+. Use app:hintTextColor attribute when text field is focused and app:textColorHint attribute when in other states. To change the bottmline color use this attribute app:boxStrokeColor as demonstrated below:

<com.google.android.material.textfield.TextInputLayout
            app:boxStrokeColor="@color/colorAccent"
            app:hintTextColor="@color/colorAccent"
            android:textColorHint="@android:color/darker_gray"
    
       <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

It works for AutoCompleteTextView as well. Hope it works for you:)

How to check if an user is logged in Symfony2 inside a controller?

It's good practise to extend from a baseController and implement some base functions implement a function to check if the user instance is null like this if the user form the Userinterface then there is no user logged in

/**

*/
class BaseController extends AbstractController
{

    /**
     * @return User

     */
    protected function getUser(): ?User
    {
        return parent::getUser();
    }

    /**
     * @return bool
     */
    protected function isUserLoggedIn(): bool
    {
        return $this->getUser() instanceof User;
    }
}

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

How to get a shell environment variable in a makefile?

for those who want some official document to confirm the behavior

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.

https://www.gnu.org/software/make/manual/html_node/Environment.html

Current date without time

This should work:

string datetime = DateTime.Today.ToString();

Two statements next to curly brace in an equation

You can try the cases env in amsmath.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  f(x)=\begin{cases}
    1, & \text{if $x<0$}.\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}

\end{document}

amsmath cases

bash, extract string before a colon

This works for me you guys can try it out

INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING

How to plot two columns of a pandas data frame using points?

Now in latest pandas you can directly use df.plot.scatter function

df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
                   [6.4, 3.2, 1], [5.9, 3.0, 2]],
                  columns=['length', 'width', 'species'])
ax1 = df.plot.scatter(x='length',
                      y='width',
                      c='DarkBlue')

https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.scatter.html

Specifying Font and Size in HTML table

The font tag has been deprecated for some time now.

That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.

And as @Alex H said, you should be using CSS for this.

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

I am not able to run my own build on the other suggestions here. I even tried different versions of maven-compiler-plugin: 3.1, 3.7.0, etc.

I made it work adding this:

<testSourceDirectory>/src/test/java</testSourceDirectory>

I tried this approach because it seems like the /src/test/java directory is considered a java class that is why it is compiled the same time as /src/test/java. So my hunch were right in my case.

Maybe it is to others too, so just try this one.

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

Here's my take on the problem. I create AbsoluteLayout overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.

Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).

Code of the demo: https://github.com/deville/info-window-demo

An article providing details (in Russian): http://habrahabr.ru/post/213415/

Random word generator- Python

get the words online

from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
print(webpage)

Randomizing the first 500 words

from urllib.request import Request, urlopen
import random


url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)

Output

['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']

VBA: How to display an error message just like the standard error message which has a "Debug" button?

First the good news. This code does what you want (please note the "line numbers")

Sub a()
 10:    On Error GoTo ErrorHandler
 20:    DivisionByZero = 1 / 0
 30:    Exit Sub
 ErrorHandler:
 41: If Err.Number <> 0 Then
 42:    Msg = "Error # " & Str(Err.Number) & " was generated by " _
         & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
 43:    MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
 44:    End If
 50:    Resume Next
 60: End Sub

When it runs, the expected MsgBox is shown:

alt text

And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.

However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.

HTH!

How to set default value to all keys of a dict object in python?

You can replace your old dictionary with a defaultdict:

>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1

The "trick" here is that a defaultdict can be initialized with another dict. This means that you preserve the existing values in your normal dict:

>>> d['foo']
123

svn: E155004: ..(path of resource).. is already locked

In my case, it worked making a merge (WinMerge in Windows, Meld in Linux) between locked project and a new project checkout. After that, I continued working on the new project checkout, and the lock problem was solved.

What is the default value for Guid?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()

default(Guid)

Guid.Empty

How to make lists contain only distinct element in Python?

The characteristics of sets in Python are that the data items in a set are unordered and duplicates are not allowed. If you try to add a data item to a set that already contains the data item, Python simply ignores it.

>>> l = ['a', 'a', 'bb', 'b', 'c', 'c', '10', '10', '8','8', 10, 10, 6, 10, 11.2, 11.2, 11, 11]
>>> distinct_l = set(l)
>>> print(distinct_l)
set(['a', '10', 'c', 'b', 6, 'bb', 10, 11, 11.2, '8'])

Why should hash functions use a prime number modulus?

It depends on the choice of hash function.

Many hash functions combine the various elements in the data by multiplying them with some factors modulo the power of two corresponding to the word size of the machine (that modulus is free by just letting the calculation overflow).

You don't want any common factor between a multiplier for a data element and the size of the hash table, because then it could happen that varying the data element doesn't spread the data over the whole table. If you choose a prime for the size of the table such a common factor is highly unlikely.

On the other hand, those factors are usually made up from odd primes, so you should also be safe using powers of two for your hash table (e.g. Eclipse uses 31 when it generates the Java hashCode() method).

Spring JSON request getting 406 (not Acceptable)

Check <mvc:annotation-driven /> in dispatcherservlet.xml , if not add it. And add

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

these dependencies in your pom.xml

Android Studio: Default project directory

At some point I too tried to do this, but the Android Studio doesn’t work quite like Eclipse does.

It's simpler: if you create a project at, say /home/USER/Projects/AndroidStudio/MyApplication from there on all new projects will default to /home/USER/Projects/AndroidStudio.

You can also edit ~/.AndroidStudioPreview/config/options/ide.general.xml (in linux) and change the line that reads <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" /> to <option name="lastProjectLocation" value="$USER_HOME$/Projects/AndroidStudio" />, but be aware that as soon as you create a project anywhere else this will change to that place and all new projects will default to it.

Hope this helps, but the truth is there really isn't much more to it other than what I explained here.

Let me know if you need anything else.

System.Net.WebException HTTP status code

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

first I had to delete my registry by using npm config delete registry and register new value using npm config set registry "http://registry.npmjs.org"

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

How to disable EditText in Android

You can try the following method :

 private void disableEditText(EditText editText) {
    editText.setFocusable(false);
    editText.setEnabled(false);
    editText.setCursorVisible(false);
    editText.setKeyListener(null);
    editText.setBackgroundColor(Color.TRANSPARENT); 
 }

Enabled EditText :

Enabled EditText

Disabled EditText :

Disabled EditText

It works for me and hope it helps you.

How to read and write to a text file in C++?

Header files needed:

#include <iostream>
#include <fstream>

declare input file stream:

ifstream in("in.txt");

declare output file stream:

ofstream out("out.txt");

if you want to use variable for a file name, instead of hardcoding it, use this:

string file_name = "my_file.txt";
ifstream in2(file_name.c_str());

reading from file into variables (assume file has 2 int variables in):

int num1,num2;
in >> num1 >> num2;

or, reading a line a time from file:

string line;
while(getline(in,line)){
//do something with the line
}

write variables back to the file:

out << num1 << num2;

close the files:

in.close();
out.close();

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

Using Math.round to round to one decimal place?

If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.

Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:

double value = 540.512 / 1978.8 * 100;
// Apache commons math
double rounded1 = Precision.round(value, 1);
double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
// Colt
double rounded3 = Functions.round(0.1).apply(value)
// Weka
double rounded4 = Utils.roundDouble(value, 1)

Maven dependencies:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.5</version>
</dependency>

<dependency>
    <groupId>colt</groupId>
    <artifactId>colt</artifactId>
    <version>1.2.0</version>
</dependency>

<dependency>
    <groupId>nz.ac.waikato.cms.weka</groupId>
    <artifactId>weka-stable</artifactId>
    <version>3.6.12</version>
</dependency>

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How to get list of all installed packages along with version in composer?

You can run composer show -i (short for --installed).

In the latest version just use composer show.

The -i options has been deprecated.

You can also use the global instalation of composer: composer global show

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

How can one grab a stack trace in C?

For the past few years I have been using Ian Lance Taylor's libbacktrace. It is much cleaner than the functions in the GNU C library which require exporting all the symbols. It provides more utility for the generation of backtraces than libunwind. And last but not least, it is not defeated by ASLR as are approaches requiring external tools such as addr2line.

Libbacktrace was initially part of the GCC distribution, but it is now made available by the author as a standalone library under a BSD license:

https://github.com/ianlancetaylor/libbacktrace

At the time of writing, I would not use anything else unless I need to generate backtraces on a platform which is not supported by libbacktrace.

Why and how to fix? IIS Express "The specified port is in use"

Visual studio 2015

  • Close all the files you have open inside Visual studio.
  • Then close application and exit Visual Studio.
  • Open Visual Studio and it should successfully run.

I hope this helps.

MySQL Workbench: How to keep the connection alive

I had a similar problem where CREATE FULLTEXT timed out after 30 seconds:

error

Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:

fix error

Also, I did not have to restart mysql workbench for this to work.

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

Applying a single font to an entire website with CSS

Please place this in the head of your Page(s) if the "body" needs the use of 1 and the same font:

<style type="text/css">
body {font-family:FONT-NAME ;
     }
</style>

Everything between the tags <body> and </body>will have the same font

Passing parameters to a JDBC PreparedStatement

Do something like this, which also prevents SQL injection attacks

statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();

AngularJS $watch window resize inside directive

// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag

---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';

@Directive({
       selector: '[resize]',
       host: { '(window:resize)': 'onResize()' } // Window resize listener
})

export class AutoResize {

element: ElementRef; // Element that associated to attribute.
$window: any;
       constructor(_element: ElementRef) {

         this.element = _element;
         // Get instance of DOM window.
         this.$window = angular.element(window);

         this.onResize();

    }

    // Adjust height of element.
    onResize() {
         $(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
   }
}

Which mime type should I use for mp3

mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130

If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.

In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How to change Apache Tomcat web server port number

Navigate to /tomcat-root/conf folder. Within you will find the server.xml file.

Open the server.xml in your preferred editor. Search the below similar statement (not exactly same as below will differ)

    <Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Going to give the port number to 9090

     <Connector port="9090" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Save the file and restart the server. Now the tomcat will listen at port 9090

How to iterate through LinkedHashMap with lists as values

// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}

Easy way of running the same junit test over and over?

Inspired by the following resources:

Example

Create and use a @Repeat annotation as follows:

public class MyTestClass {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(10)
    public void testMyCode() {
        //your test code goes here
    }
}

Repeat.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;
        }

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

    @Override
    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        }
        return result;
    }
}

PowerMock

Using this solution with @RunWith(PowerMockRunner.class), requires updating to Powermock 1.6.5 (which includes a patch).

String escape into XML

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

What is the best way to get all the divisors of a number?

My solution via generator function is:

def divisor(num):
    for x in range(1, num + 1):
        if num % x == 0:
            yield x
    while True:
        yield None

Javascript change Div style

function abc() {
    var color = document.getElementById("test").style.color;
    if (color === "red")
         document.getElementById("test").style.color="black";
    else
         document.getElementById("test").style.color="red";
}

Exit a while loop in VBS/VBA

Incredibly old question, but bearing in mind that the OP said he does not want to use Do While and that none of the other solutions really work... Here's something that does exactly the same as a Exit Loop:

This never runs anything if the status is already at "Fail"...

While (i < 20 And Not bShouldStop)
    If (Status = "Fail") Then
        bShouldStop = True
    Else
        i = i + 1
        '
        ' Do Something
        '
    End If  
Wend

Whereas this one always processes something first (and increment the loop variable) before deciding whether it should loop once more or not.

While (i < 20 And Not bShouldStop)
    i = i + 1
    '
    ' Do Something
    '

    If (Status = "Fail") Then
        bShouldStop = True
    End If  
Wend

Ultimately, if the variable Status is being modified inside the While (and assuming you don't need i outside the while, it makes no difference really, but just wanted to present multiple options...

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

How can I represent a range in Java?

import java.util.Arrays;

class Soft{
    public static void main(String[] args){
        int[] nums=range(9, 12);
        System.out.println(Arrays.toString(nums));
    }
    static int[] range(int low, int high){
        int[] a=new int[high-low];
        for(int i=0,j=low;i<high-low;i++,j++){
            a[i]=j;
        }
        return a;

    }
}

My code is similar to Python`s range :)

How can I append a query parameter to an existing URL?

For android, Use: https://developer.android.com/reference/android/net/Uri#buildUpon()

URI oldUri = new URI(uri);
Uri.Builder builder = oldUri.buildUpon();
 builder.appendQueryParameter("newParameter", "dummyvalue");
 Uri newUri =  builder.build();

How to disable CSS in Browser for testing purposes

Actually, it's easier than you think. In any browsers press F12 to bring up the debug console. This works for IE, Firefox, and Chrome. Not sure about Opera. Then comment out the CSS in the element windows. That's it.

How to set the first option on a select box using jQuery?

If you just want to reset the select element to it's first position, the simplest way may be:

$('#name2').val('');

To reset all select elements in the document:

$('select').val('')

EDIT: To clarify as per a comment below, this resets the select element to its first blank entry and only if a blank entry exists in the list.

Composer install error - requires ext_curl when it's actually enabled

According to https://github.com/composer/composer/issues/2119 you could extend your local composer.json to state that it provides the extension (which it doesn't really do - that's why you shouldn't publicly publish your package, only use it internally).

Convert Select Columns in Pandas Dataframe to Numpy Array

The columns parameter accepts a collection of column names. You're passing a list containing a dataframe with two rows:

>>> [df[1:]]
[  viz  a1_count  a1_mean  a1_std
1   n         0      NaN     NaN
2   n         2       51      50]
>>> df.as_matrix(columns=[df[1:]])
array([[ nan,  nan],
       [ nan,  nan],
       [ nan,  nan]])

Instead, pass the column names you want:

>>> df.columns[1:]
Index(['a1_count', 'a1_mean', 'a1_std'], dtype='object')
>>> df.as_matrix(columns=df.columns[1:])
array([[  3.      ,   2.      ,   0.816497],
       [  0.      ,        nan,        nan],
       [  2.      ,  51.      ,  50.      ]])

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

SPAN vs DIV (inline-block)

I know this Q is old, but why not use all DIVs instead of the SPANs? Then everything plays all happy together.

Example:

<div> 
   <div> content1(divs,p, spans, etc) </div> 
   <div> content2(divs,p, spans, etc) </div> 
   <div> content3(divs,p, spans, etc) </div> 
</div> 
<div> 
   <div> content4(divs,p, spans, etc) </div> 
   <div> content5(divs,p, spans, etc) </div> 
   <div> content6(divs,p, spans, etc) </div> 
</div>

Extract time from date String

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

How to read a text file directly from Internet using Java?

I did that in the following way for an image, you should be able to do it for text using similar steps.

// folder & name of image on PC          
File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 

Boolean testB = fileObj.createNewFile();

System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);

// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
InputStream webIS = url.openStream();

FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
    c = webIS.read();
    System.out.println("==============> " + c);
    if (c !=-1) {
        fo.write((byte) c);
    }
} while(c != -1);

webIS.close();
fo.close();

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

How do I measure request and response times at once using cURL?

This is a modified version of Simons answer which makes the multi-lined output a single line. It also introduces the current timestamp so it's easier to follow each line of output.

Sample format fle
$ cat time-format.txt
time_namelookup:%{time_namelookup} time_connect:%{time_connect} time_appconnect:%{time_appconnect} time_pretransfer:%{time_pretransfer} time_redirect:%{time_redirect} time_starttransfer:%{time_starttransfer} time_total:%{time_total}\n
example cmd
$ while [ 1 ];do echo -n "$(date) - " ; curl -w @time-format.txt -o /dev/null -s https://myapp.mydom.com/v1/endpt-http; sleep 1; done | grep -v time_total:0
results
Mon Dec 16 17:51:47 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:1.666 time_total:1.666
Mon Dec 16 17:51:50 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:3.794 time_total:3.795
Mon Dec 16 17:51:55 UTC 2019 - time_namelookup:0.004 time_connect:0.017 time_appconnect:0.175 time_pretransfer:0.175 time_redirect:0.000 time_starttransfer:1.971 time_total:1.971
Mon Dec 16 17:51:58 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.173 time_pretransfer:0.173 time_redirect:0.000 time_starttransfer:1.161 time_total:1.161
Mon Dec 16 17:52:00 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.166 time_pretransfer:0.167 time_redirect:0.000 time_starttransfer:1.434 time_total:1.434
Mon Dec 16 17:52:02 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.177 time_pretransfer:0.177 time_redirect:0.000 time_starttransfer:5.119 time_total:5.119
Mon Dec 16 17:52:08 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.172 time_pretransfer:0.172 time_redirect:0.000 time_starttransfer:30.185 time_total:30.185
Mon Dec 16 17:52:39 UTC 2019 - time_namelookup:0.004 time_connect:0.014 time_appconnect:0.164 time_pretransfer:0.164 time_redirect:0.000 time_starttransfer:30.175 time_total:30.176
Mon Dec 16 17:54:28 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:3.191 time_pretransfer:3.191 time_redirect:0.000 time_starttransfer:3.212 time_total:3.212
Mon Dec 16 17:56:08 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:1.184 time_pretransfer:1.184 time_redirect:0.000 time_starttransfer:1.215 time_total:1.215
Mon Dec 16 18:00:24 UTC 2019 - time_namelookup:0.004 time_connect:0.015 time_appconnect:0.181 time_pretransfer:0.181 time_redirect:0.000 time_starttransfer:1.267 time_total:1.267

I used the above to catch slow responses on the above endpoint.

HTML code for INR

SPAN class code. Stylesheet:

<link rel="stylesheet" type="text/css" href="http://cdn.webrupee.com/font">

Now use the below mentioned code to type Indian Rupee symbol,

<span class="WebRupee">Rs.</span>

Once the popular font families will be updated to Unicode 6.0.0, then you will be able to type Indian Rupee Symbol by typing ₹ in HTML editor.

Jquery Chosen plugin - dynamically populate list by Ajax

try this:

$('.chzn-choices input').autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "/change/name/autocomplete/"+request.term+"/",
      dataType: "json",
      beforeSend: function(){$('ul.chzn-results').empty();},
      success: function( data ) {
        response( $.map( data, function( item ) {
          $('ul.chzn-results').append('<li class="active-result">' + item.name + '</li>');
        }));
      }
    });
  }
});

How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

Node.js version on the command line? (not the REPL)

On an Arm7 (armhf) device running Debian Stretch, I had to issue either of the following:

$ nodejs -v
$ nodejs -h

The following did not work:

$ node -v
$ node -h
$ apm -v

Hope this helps someone else.

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

Parse large JSON file in Nodejs

To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):

var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';

stream.on('data', function(d) {
    buf += d.toString(); // when data is read, stash it in a string buffer
    pump(); // then process the buffer
});

function pump() {
    var pos;

    while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
        if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
            buf = buf.slice(1); // discard it
            continue; // so that the next iteration will start with data
        }
        processLine(buf.slice(0,pos)); // hand off the line
        buf = buf.slice(pos+1); // and slice the processed data off the buffer
    }
}

function processLine(line) { // here's where we do something with a line

    if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)

    if (line.length > 0) { // ignore empty lines
        var obj = JSON.parse(line); // parse the JSON
        console.log(obj); // do something with the data here!
    }
}

Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump is called.

If there's no newline in the buffer, pump simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.

If there is a newline, pump slices off the buffer from the beginning to the newline and hands it off to process. It then checks again if there's another newline in the buffer (the while loop). In this way, we can process all of the lines that were read in the current chunk.

Finally, process is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse one the line. At this point, you can do whatever you need to with your object.

Note that JSON.parse is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'} will throw an error; you must use {"name":"thing1"}.

Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.

How to retrieve a file from a server via SFTP?

hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)

Example code from SFTPUpload.java

package net.schmizz.sshj.examples;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;

import java.io.File;
import java.io.IOException;

/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {

    public static void main(String[] args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();
        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final String src = System.getProperty("user.home") + File.separator + "test_file";
            final SFTPClient sftp = ssh.newSFTPClient();
            try {
                sftp.put(new FileSystemFile(src), "/tmp");
            } finally {
                sftp.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

}

Why can I not push_back a unique_ptr into a vector?

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

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

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

The following works with the new emplace calls.

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

See using unique_ptr with standard library containers for further reading.

How to resize images proportionally / keeping the aspect ratio?

This should work for images with all possible proportions

$(document).ready(function() {
    $('.list img').each(function() {
        var maxWidth = 100;
        var maxHeight = 100;
        var width = $(this).width();
        var height = $(this).height();
        var ratioW = maxWidth / width;  // Width ratio
        var ratioH = maxHeight / height;  // Height ratio

        // If height ratio is bigger then we need to scale height
        if(ratioH > ratioW){
            $(this).css("width", maxWidth);
            $(this).css("height", height * ratioW);  // Scale height according to width ratio
        }
        else{ // otherwise we scale width
            $(this).css("height", maxHeight);
            $(this).css("width", height * ratioH);  // according to height ratio
        }
    });
});

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Represent space and tab in XML tag

Work for me

\n = &#xA;
\r = &#xD;
\t = &#x9;
space = &#x20;

Here is an example on how to use them in XML

<KeyWord name="hello&#x9;" />

SQL Select between dates

SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')

Note that I use the format : dd/mm/yyyy

If you use d/m/yyyy, Change in substr()

Hope this will help you.

How to make grep only match if the entire line matches?

I intend to add some extra explanation regarding the attempts of OP and other answers as well.

You can use John Kugelmans' solution like this too:

grep -x "ABB\.log" a.tmp

quoting the string and escaping the dot (.) makes it to not need the -F flag any more.

You need to escape the . (dot) (because it matches any character (not only .) if not escaped) or use the -F flag with grep. -F flag makes it a fixed string (not a regex).

If you don't quote the string, you may need double backslash to escape the dot (.):

grep -x ABB\\.log a.tmp


Test:

$ echo "ABBElog"|grep -x  ABB.log
ABBElog #matched !!!
$ echo "ABBElog"|grep -x  "ABB\.log"
#returns empty string, no match


Note:

  1. -x forces to match the whole line.
  2. Answers using a non escaped . without -F flag are wrong.
  3. You can avoid -x switch by wrapping your pattern string with ^ and $. In this case make sure you don't use -F, instead escape the ., because -F will prevent the regex interpretation of ^ and $.


EDIT: (Adding extra explanation in regards of @hakre ):

If you want to match a string starting with -, then you should use -- with grep. Whatever follows -- will be taken as an input (not option).

Example:

echo -f |grep -- "-f"     # where grep "-f" will show error
echo -f |grep -F -- "-f"  # whre grep -F "-f" will show error
grep "pat" -- "-file"     # grep "pat" "-file" won't work. -file is the filename

Manually Triggering Form Validation using jQuery

For input field

<input id="PrimaryPhNumber" type="text" name="mobile"  required
                                       pattern="^[789]\d{9}$" minlenght="10" maxLength="10" placeholder="Eg: 9444400000"
                                       class="inputBoxCss"/>
$('#PrimaryPhNumber').keyup(function (e) {
        console.log(e)
        let field=$(this)
        if(Number(field.val()).toString()=="NaN"){
            field.val('');
            field.focus();
            field[0].setCustomValidity('Please enter a valid phone number');
            field[0].reportValidity()
            $(":focus").css("border", "2px solid red");
        }
    })

How to remove anaconda from windows completely?

Go to C:\Users\username\Anaconda3 and search for Uninstall-Anaconda3.exe which will remove all the components of Anaconda.

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

Javascript Regexp dynamic generation from variables?

The RegExp constructor creates a regular expression object for matching text with a pattern.

    var pattern1 = ':\\(|:=\\(|:-\\(';
    var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
    var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
    str.match(regex);

Above code works perfectly for me...

How can I permanently enable line numbers in IntelliJ?

IntelliJ 14.X Onwards

From version 14.0 onwards, the path to the setting dialog is slightly different, a General submenu has been added between Editor and Appearance as shown below

enter image description here

IntelliJ 8.1.2 - 13.X

From IntelliJ 8.1.2 onwards, this option is in File | Settings1. Within the IDE Settings section of that dialog, you'll find it under Editor | Appearance.

  1. On a Mac, these are named IntelliJ IDEA | Preferences...

enter image description here