Programs & Examples On #Page jump

A page jump refers to the sudden change in the scroll position of the document that's loaded in a browser.

How add class='active' to html menu with php

CALL common.php
<style>
    .ddsmoothmenu ul li{float: left; padding: 0 20px;}
    .ddsmoothmenu ul li a{display: block;
  padding: 40px 15px 20px 15px;
  color: #4b4b4b;
  font-size: 13px;
  font-family: 'Open Sans', Arial, sans-serif;
  text-align: right;
  text-transform: uppercase;
  margin-left: 1px; color: #fff; background: #000;}
    .current .test{  background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php" class="test">Home  <i>::</i> <span>welcome</span></a></li>
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>"><a href="about.php" class="test">About us <i>::</i> <span>Who we are</span></a></li>
    <li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>"><a href="course.php">Our Courses  <i>::</i> <span>What we do</span></a></li>
</ul><!-- end #dropdown-menu -->

</div><!-- end .span8 -->

add each page
<?php include('common.php'); ?>

How to go from Blob to ArrayBuffer

The Response API consumes a (immutable) Blob from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer, and here's a demonstration of it.

var blob = GetABlobSomehow();

// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
await new Response(blob).arrayBuffer();   //=> <ArrayBuffer>

alternatively you could use this:

new Response(blob).arrayBuffer()
.then(/* <function> */);

Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)

How to vertically center a <span> inside a div?

At your parent DIV add

display:table;

and at your child element add

 display:table-cell;
 vertical-align:middle;

How do I update the GUI from another thread?

Handling long work

Since .NET 4.5 and C# 5.0 you should use Task-based Asynchronous Pattern (TAP) along with async-await keywords in all areas (including the GUI):

TAP is the recommended asynchronous design pattern for new development

instead of Asynchronous Programming Model (APM) and Event-based Asynchronous Pattern (EAP) (the latter includes the BackgroundWorker Class).

Then, the recommended solution for new development is:

  1. Asynchronous implementation of an event handler (Yes, that's all):

    private async void Button_Clicked(object sender, EventArgs e)
    {
        var progress = new Progress<string>(s => label.Text = s);
        await Task.Factory.StartNew(() => SecondThreadConcern.LongWork(progress),
                                    TaskCreationOptions.LongRunning);
        label.Text = "completed";
    }
    
  2. Implementation of the second thread that notifies the UI thread:

    class SecondThreadConcern
    {
        public static void LongWork(IProgress<string> progress)
        {
            // Perform a long running work...
            for (var i = 0; i < 10; i++)
            {
                Task.Delay(500).Wait();
                progress.Report(i.ToString());
            }
        }
    }
    

Notice the following:

  1. Short and clean code written in sequential manner without callbacks and explicit threads.
  2. Task instead of Thread.
  3. async keyword, that allows to use await which in turn prevent the event handler from reaching the completion state till the task finished and in the meantime doesn't block the UI thread.
  4. Progress class (see IProgress Interface) that supports Separation of Concerns (SoC) design principle and doesn't require explicit dispatcher and invoking. It uses the current SynchronizationContext from its creation place (here the UI thread).
  5. TaskCreationOptions.LongRunning that hints to do not queue the task into ThreadPool.

For a more verbose examples see: The Future of C#: Good things come to those who 'await' by Joseph Albahari.

See also about UI Threading Model concept.

Handling exceptions

The below snippet is an example of how to handle exceptions and toggle button's Enabled property to prevent multiple clicks during background execution.

private async void Button_Click(object sender, EventArgs e)
{
    button.Enabled = false;

    try
    {
        var progress = new Progress<string>(s => button.Text = s);
        await Task.Run(() => SecondThreadConcern.FailingWork(progress));
        button.Text = "Completed";
    }
    catch(Exception exception)
    {
        button.Text = "Failed: " + exception.Message;
    }

    button.Enabled = true;
}

class SecondThreadConcern
{
    public static void FailingWork(IProgress<string> progress)
    {
        progress.Report("I will fail in...");
        Task.Delay(500).Wait();

        for (var i = 0; i < 3; i++)
        {
            progress.Report((3 - i).ToString());
            Task.Delay(500).Wait();
        }

        throw new Exception("Oops...");
    }
}

Where is a log file with logs from a container?

To directly view the logfile in less, I use:

docker inspect $1 | grep 'LogPath' | sed -n "s/^.*\(\/var.*\)\",$/\1/p" | xargs sudo less

run as ./viewLogs.sh CONTAINERNAME

How to append data to div using JavaScript?

java script

document.getElementById("divID").html("this text will be added to div");

jquery

$("#divID").html("this text will be added to div");

Use .html() without any arguments to see that you have entered. You can use the browser console to quickly test these functions before using them in your code.

Best way to add Gradle support to IntelliJ Project

To add to other answers. For me it was helpful to delete .mvn directory and then add build.gradle. New versions of IntelliJ will then automatically notice that you use Gradle.

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them).

Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity.

The following code runs as expected, even in a console application:

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://tempuri.org", ""),
    new HttpResponse(new StringWriter())
    );

// User is logged in
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity("username"),
    new string[0]
    );

// User is logged out
HttpContext.Current.User = new GenericPrincipal(
    new GenericIdentity(String.Empty),
    new string[0]
    );

Launching an application (.EXE) from C#?

Here's a snippet of helpful code:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.

Named parameters in JDBC

Vanilla JDBC only supports named parameters in a CallableStatement (e.g. setString("name", name)), and even then, I suspect the underlying stored procedure implementation has to support it.

An example of how to use named parameters:

//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
        + "if @id is not null "
        + "select * from sysobjects where id = @id "
        + "else if @name is not null "
        + "select * from sysobjects where name = @name "
        + " end");
stmt.execute();

//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}


//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}

Extracting hours from a DateTime (SQL Server 2005)

I can't extract hours, with HOUR(Date())

There is a way to call HOUR (I would not recommend to use it though because there is DATEPART function) using ODBC Scalar Functions:

SELECT {fn HOUR(GETDATE())} AS hour

LiveDemo

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

You can use a union:

INSERT INTO dbo.MyTable (ID, Name) 
SELECT ID, Name FROM (
    SELECT 123, 'Timmy'
    UNION ALL
    SELECT 124, 'Jonny'
    UNION ALL
    SELECT 125, 'Sally'
) AS X (ID, Name)

Sort an array of objects in React and render them

Chrome browser considers integer value as return type not boolean value so,

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM ? 1:-1).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How can I recursively find all files in current and subfolders based on wildcard matching?

find will find all files that match a pattern:

find . -name "*foo"

However, if you want a picture:

tree -P "*foo"

Hope this helps!

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

How can I output the value of an enum class in C++11

It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).

The solution is to write a generic operator<< function which will work for any scoped enum. The solution employs SFINAE via std::enable_if and is as follows.

#include <iostream>
#include <type_traits>

// Scoped enum
enum class Color
{
    Red,
    Green,
    Blue
};

// Unscoped enum
enum Orientation
{
    Horizontal,
    Vertical
};

// Another scoped enum
enum class ExecStatus
{
    Idle,
    Started,
    Running
};

template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
    return stream << static_cast<typename std::underlying_type<T>::type>(e);
}

int main()
{
    std::cout << Color::Blue << "\n";
    std::cout << Vertical << "\n";
    std::cout << ExecStatus::Running << "\n";
    return 0;
}

How to find locked rows in Oracle

you can find the locked tables in oralce by querying with following query

    select
   c.owner,
   c.object_name,
   c.object_type,
   b.sid,
   b.serial#,
   b.status,
   b.osuser,
   b.machine
from
   v$locked_object a ,
   v$session b,
   dba_objects c
where
   b.sid = a.session_id
and
   a.object_id = c.object_id;

Problem in running .net framework 4.0 website on iis 7.0

After mapping of Application follow these steps

Open IIS Click on Applications Pools Double click on website Change Manage pipeline mode to "classic" click Ok.

Ow change .Net Framework Version to Lower version

Then click Ok

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Changing the highlight color when selecting text in an HTML text input

All answers here are correct when it comes to the ::selection pseudo element, and how it works. However, the question does in fact specifically ask how to use it on text inputs.

The only way to do that is to apply the rule via a parent of the input (any parent for that matter):

_x000D_
_x000D_
.parent ::-webkit-selection, [contenteditable]::-webkit-selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
.parent ::-moz-selection, [contenteditable]::-moz-selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
.parent ::selection, [contenteditable]::selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
/* Aesthetics */_x000D_
input, [contenteditable] {_x000D_
  border:1px solid black;_x000D_
  display:inline-block;_x000D_
  width: 150px;_x000D_
  height: 20px;_x000D_
  line-height: 20px;_x000D_
  padding: 3px;_x000D_
}
_x000D_
<span class="parent"><input type="text" value="Input" /></span>_x000D_
<span contenteditable>Content Editable</span>
_x000D_
_x000D_
_x000D_

Environment variables in Eclipse

You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.

Select the JRE you use for running programs in Eclipse

Sending the value for hadoop.home.dir property as a VM argument

Checking for a null object in C++

A C++ reference is not a pointer nor a Java/C# style reference and cannot be NULL. They behave as if they were an alias to another existing object.

In some cases, if there are bugs in your code, you might get a reference into an already dead or non-existent object, but the best thing you can do is hope that the program dies soon enough to be able to debug what happened and why your program got corrupted.

That is, I have seen code checking for 'null references' doing something like: if ( &reference == 0 ), but the standard is clear that there cannot be null references in a well-formed program. If a reference is bound to a null object the program is ill-formed and should be corrected. If you need optional values, use pointers (or some higher level construct like boost::optional), not references.

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

Why are iframes considered dangerous and a security risk?

As soon as you're displaying content from another domain, you're basically trusting that domain not to serve-up malware.

There's nothing wrong with iframes per se. If you control the content of the iframe, they're perfectly safe.

How to find the highest value of a column in a data frame in R?

There is a package matrixStats that provides some functions to do column and row summaries, see in the package vignette, but you have to convert your data.frame into a matrix.

Then you run: colMaxs(as.matrix(ozone))

Difference between dates in JavaScript

I have found this and it works fine for me:

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Reference

Add/Delete table rows dynamically using JavaScript

You could just clone the first row that has the inputs, then get the nested inputs and update their ID to add the row number (and do the same with the first cell).

function deleteRow(row)
{
    var i=row.parentNode.parentNode.rowIndex;
    document.getElementById('POITable').deleteRow(i);
}


function insRow()
{
    var x=document.getElementById('POITable');
       // deep clone the targeted row
    var new_row = x.rows[1].cloneNode(true);
       // get the total number of rows
    var len = x.rows.length;
       // set the innerHTML of the first row 
    new_row.cells[0].innerHTML = len;

       // grab the input from the first cell and update its ID and value
    var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
    inp1.id += len;
    inp1.value = '';

       // grab the input from the first cell and update its ID and value
    var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
    inp2.id += len;
    inp2.value = '';

       // append the new row to the table
    x.appendChild( new_row );
}

Demo below

_x000D_
_x000D_
function deleteRow(row) {_x000D_
  var i = row.parentNode.parentNode.rowIndex;_x000D_
  document.getElementById('POITable').deleteRow(i);_x000D_
}_x000D_
_x000D_
_x000D_
function insRow() {_x000D_
  console.log('hi');_x000D_
  var x = document.getElementById('POITable');_x000D_
  var new_row = x.rows[1].cloneNode(true);_x000D_
  var len = x.rows.length;_x000D_
  new_row.cells[0].innerHTML = len;_x000D_
_x000D_
  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];_x000D_
  inp1.id += len;_x000D_
  inp1.value = '';_x000D_
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];_x000D_
  inp2.id += len;_x000D_
  inp2.value = '';_x000D_
  x.appendChild(new_row);_x000D_
}
_x000D_
<div id="POItablediv">_x000D_
  <input type="button" id="addPOIbutton" value="Add POIs" /><br/><br/>_x000D_
  <table id="POITable" border="1">_x000D_
    <tr>_x000D_
      <td>POI</td>_x000D_
      <td>Latitude</td>_x000D_
      <td>Longitude</td>_x000D_
      <td>Delete?</td>_x000D_
      <td>Add Rows?</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td><input size=25 type="text" id="latbox" /></td>_x000D_
      <td><input size=25 type="text" id="lngbox" readonly=true/></td>_x000D_
      <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" /></td>_x000D_
      <td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()" /></td>_x000D_
    </tr>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

"could not find stored procedure"

One more possibility to check. Listing here because it just happened to me and wasn't mentioned;-)

I had accidentally added a space character on the end of the name. Many hours of trying things before I finally noticed it. It's always something simple after you figure it out.

How to redirect user's browser URL to a different page in Nodejs?

response.writeHead(301,
  {Location: 'http://whateverhostthiswillbe:8675/'+newRoom}
);
response.end();

row-level trigger vs statement-level trigger

1)row level trigger is used to perform action on set of rows as insert , update or delete

example:-you have to delete a set of rows and simultaneously that deleted rows must also inserted in new table for audit purpose;

2)statement level trigger:- it generally used to imposed restriction on the event you are performing.

example:- restriction to delete the data between 10 pm and 6 am;

hope this helps:)

"CSV file does not exist" for a filename with embedded quotes

I am using a Mac. I had the same problem wherein .csv file was in the same folder where the python script was placed, however, Spyder still was unable to locate the file. I changed the file name from capital letters to all small letters and it worked.

Send cookies with curl

You can use -b to specify a cookie file to read the cookies from as well.

In many situations using -c and -b to the same file is what you want:

curl -b cookies.txt -c cookies.txt http://example.com

Further

Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.

The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.

See Also

The cookies chapter in the Everything curl book.

Grant Select on a view not base table when base table is in a different database

I tried this in one of my databases.

To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.

Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.

What is tail recursion?

Recursion means a function calling itself. For example:

(define (un-ended name)
  (un-ended 'me)
  (print "How can I get here?"))

Tail-Recursion means the recursion that conclude the function:

(define (un-ended name)
  (print "hello")
  (un-ended 'me))

See, the last thing un-ended function (procedure, in Scheme jargon) does is to call itself. Another (more useful) example is:

(define (map lst op)
  (define (helper done left)
    (if (nil? left)
        done
        (helper (cons (op (car left))
                      done)
                (cdr left))))
  (reverse (helper '() lst)))

In the helper procedure, the LAST thing it does if the left is not nil is to call itself (AFTER cons something and cdr something). This is basically how you map a list.

The tail-recursion has a great advantage that the interpreter (or compiler, dependent on the language and vendor) can optimize it, and transform it into something equivalent to a while loop. As matter of fact, in Scheme tradition, most "for" and "while" loop is done in a tail-recursion manner (there is no for and while, as far as I know).

How to bind a List<string> to a DataGridView control?

Try this :

//i have a 
List<string> g_list = new List<string>();

//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");

//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
    dataGridView1.Rows.Add(l_str);
}

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

How do I prevent CSS inheritance?

There is a property called all in the CSS3 inheritance module. It works like this:

#sidebar ul li {
  all: initial;
}

As of 2016-12, all browsers but IE/Edge and Opera Mini support this property.

What happens to a declared, uninitialized variable in C? Does it have a value?

If storage class is static or global then during loading, the BSS initialises the variable or memory location(ML) to 0 unless the variable is initially assigned some value. In case of local uninitialized variables the trap representation is assigned to memory location. So if any of your registers containing important info is overwritten by compiler the program may crash.

but some compilers may have mechanism to avoid such a problem.

I was working with nec v850 series when i realised There is trap representation which has bit patterns that represent undefined values for data types except for char. When i took a uninitialized char i got a zero default value due to trap representation. This might be useful for any1 using necv850es

Reason to Pass a Pointer by Reference in C++?

One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.

In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.

jQuery hasClass() - check for more than one class

jQuery

if( ['class', 'class2'].some(c => [...element[0].classList].includes(c)) )

Vanilla JS

if( ['class', 'class2'].some(c => [...element.classList].includes(c)) )

How to hide axes and gridlines in Matplotlib (python)

Turn the axes off with:

plt.axis('off')

And gridlines with:

plt.grid(b=None)

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

EditText underline below text property

Use android:backgroundTint="" in your EditText xml layout.

For api<21 you can use AppCompatEditText from support library thenapp:backgroundTint=""

Show loading image while $.ajax is performed

You can add ajax start and complete event, this is work for when you click on button event

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });

How to change href attribute using JavaScript after opening the link in a new window?

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

MongoDB query with an 'or' condition

Query objects in Mongo by default AND expressions together. Mongo currently does not include an OR operator for such queries, however there are ways to express such queries.

Use "in" or "where".

Its gonna be something like this:

db.mycollection.find( { $where : function() { 
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );

Missing MVC template in Visual Studio 2015

Just got the same issue after installing Developer Tools Microsoft ASP.NET and Web Tools 2015 (Beta7). I tried to reinstall ASP.NET Project Templates but it didn't help.

While looking into "Add / remove programs" -> "Visual 2015" -> "Modify" , I found the "Web developer tools" unchecked. This SO answer helps me to figure this.

After reinstalling this, everything reappears

enter image description here

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

How to return a struct from a function in C++?

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

JQuery Number Formatting

Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber(); concept together, you may use the following line of code;

e.g. <td class="number">1172907.50</td> will be formatted like <td class="number">1,172,907.50</td>

$('.number').text(function () { 
    var str = $(this).html() + ''; 
    x = str.split('.'); 
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    $(this).html(x1 + x2); 
});

React component initialize state from props

YOU HAVE TO BE CAREFUL when you initialize state from props in constructor. Even if props changed to new one, the state wouldn't be changed because mount never happen again. So getDerivedStateFromProps exists for that.

class FirstComponent extends React.Component {
    state = {
        description: ""
    };
    
    static getDerivedStateFromProps(nextProps, prevState) {
        if (prevState.description !== nextProps.description) {
          return { description: nextProps.description };
        }
    
        return null;
    }

    render() {
        const {state: {description}} = this;    

        return (
            <input type="text" value={description} /> 
        );
    }
}

Or use key props as a trigger to initialize:

class SecondComponent extends React.Component {
  state = {
    // initialize using props
  };
}
<SecondComponent key={something} ... />

In the code above, if something changed, then SecondComponent will re-mount as a new instance and state will be initialized by props.

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

This could be an error in the web.config file.

Open up your URL in your browser, example:

http://localhost:61277/Email.svc

Check if you have a 500 Error.

HTTP Error 500.19 - Internal Server Error

Look for the error in these sections:

Config Error

Config File

find -exec with multiple commands

There's an easier way:

find ... | while read -r file; do
    echo "look at my $file, my $file is amazing";
done

Alternatively:

while read -r file; do
    echo "look at my $file, my $file is amazing";
done <<< "$(find ...)"

How to restore PostgreSQL dump file into Postgres databases?

I find that psql.exe is quite picky with the slash direction, at least on windows (which the above looks like).

Here's an example. In a cmd window:

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres
psql (9.2.4)
Type "help" for help.

postgres=# \i c:\temp\try1.sql    
c:: Permission denied
postgres=# \i c:/temp/try1.sql
CREATE TABLE
postgres=#

You can see it fails when I use "normal" windows slashes in a \i call. However both slash styles work if you pass them as input params to psql.exe, for example:

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:\TEMP\try1.sql
CREATE TABLE

C:\Program Files\PostgreSQL\9.2\bin>psql.exe -U postgres -f c:/TEMP/try1.sql
CREATE TABLE

C:\Program Files\PostgreSQL\9.2\bin>

Causes of getting a java.lang.VerifyError

After updating Gradle in Android Studio 3.6.1 crashes happened on API 19 in release build.

There was a Glide library error. Solution is to rewrite proguard-rules.txt.

Also downgrading Gradle works (classpath 'com.android.tools.build:gradle:3.5.3'), but it is an outdated solution, don't use it.

How to check if curl is enabled or disabled

you can check by putting these code in php file.

<?php
if(in_array  ('curl', get_loaded_extensions())) {
    echo "CURL is available on your web server";
}
else{
    echo "CURL is not available on your web server";
}

OR

var_dump(extension_loaded('curl'));

How to COUNT rows within EntityFramework without loading contents?

I think you want something like

var count = context.MyTable.Count(t => t.MyContainer.ID == '1');

(edited to reflect comments)

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

getOutputStream() has already been called for this response

JSP is s presentation framework, and is generally not supposed to contain any program logic in it. As skaffman suggested, use pure servlets, or any MVC web framework in order to achieve what you want.

GetElementByID - Multiple IDs

This will not work, getElementById will query only one element by time.

You can use document.querySelectorAll("#myCircle1, #myCircle2") for querying more then one element.

ES6 or newer

With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.

Example:

const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];

// Now you can use cool array prototypes
elementsArray.forEach(element => {
    console.log(element);
});

How to query a list of IDs in ES6

Another easy way if you have an array of IDs is to use the language to build your query, example:

const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));

Read entire file in Scala?

you can also use Path from scala io to read and process files.

import scalax.file.Path

Now you can get file path using this:-

val filePath = Path("path_of_file_to_b_read", '/')
val lines = file.lines(includeTerminator = true)

You can also Include terminators but by default it is set to false..

jQuery: checking if the value of a field is null (empty)

I would also trim the input field, cause a space could make it look like filled

if ($.trim($('#person_data[document_type]').val()) != '')
{

}

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

PostgreSQL Forging Key DELETE, UPDATE CASCADE

CREATE TABLE apps_user(
  user_id SERIAL PRIMARY KEY,
  username character varying(30),
  userpass character varying(50),
  created_on DATE
);

CREATE TABLE apps_profile(
    pro_id SERIAL PRIMARY KEY,
    user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
    firstname VARCHAR(30),
    lastname VARCHAR(50),
    email VARCHAR UNIQUE,
    dob DATE
);

What is the difference between baud rate and bit rate?

I don't understand why everyone is making this complicated (answers).

I'll just leave this here.

bit rate vs. baud rate

So above would be:

  • Signal Unit: 4 bits
  • Baud Rate [Signal Units per second]: 1000 Bd (baud)
  • Bit Rate [Baud Rate * Signal Unit]: 4000 bps (bits per second)

Bit rate and Baud rate, these two terms are often used in data communication. Bit rate is simply the number of bits (i.e., 0’s and 1’s) transmitted per unit time. While Baud rate is the number of signal units transmitted per unit time that is needed to represent those bits.

How and when to use ‘async’ and ‘await’

This answer aims to provide some info specific to ASP.NET.

By utilizing async/await in MVC controller, it is possible to increase thread pool utilization and achieve a much better throughput, as explained in the below article,

http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

In web applications that sees a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making these web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

With Nodejs, if you are using routers, make sure to add cors before the routers. Otherwise, you'll still get the cors error. Like below:

const cors = require('cors');

const userRouter = require('./routers/user');

expressApp = express();
expressApp.use(cors());
expressApp.use(express.json());
expressApp.use(userRouter);

How to embed fonts in CSS?

I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.

@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'), 
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

My Routes are Returning a 404, How can I Fix Them?

The Main problem of route not working is there is mod_rewrite.so module in macos, linux not enabled in httpd.conf file of apache configuration, so can .htaccess to work. i have solved this by uncomment the line :

# LoadModule rewrite_module libexec/apache2/mod_rewrite.so

Remove the # from above line of httpdf.conf. Then it will works.
enjoy!

How to search a string in multiple files and return the names of files in Powershell?

Get-ChildItem -r | ? {$_.psiscontainer -eq $false} | ? {gc $_.pspath |select-string -pattern "dummy"}

This will give you the full details of all files

How do you tell if a checkbox is selected in Selenium for Java?

The mechanism of selenium framework:

Here selenium make request to the its server and fetch first subelement with tagname input

WebElement e = e.findElement(By.tagName("input"));

Than you try to receive attribute on that element

object attribute = e.getAttribute("checked")

So either use

findElement(By.attribute("checked")

or use

findElement(By.xpath("\\input[@checked='true']")

P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.

How to programmatically take a screenshot on Android?

You can try to do something like this,

Getting a bitmap cache from a layout or a view by doing something like First you gotta setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)

then

Bitmap bm = layout.getDrawingCache()

Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.

Assign a variable inside a Block to a variable outside a Block

Try __weak if you get any warning regarding retain cycle else use __block

Person *strongPerson = [Person new];
__weak Person *weakPerson = person;

Now you can refer weakPerson object inside block.

JavaScript seconds to time string with format hh:mm:ss

I'd upvote artem's answer, but I am a new poster. I did expand on his solution, though not what the OP asked for as follows

    t=(new Date()).toString().split(" ");
    timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);

To get

04Oct 16:31:28 PDT

This works for me...

But if you are starting with just a time quantity, I use two functions; one to format and pad, and one to calculate:

function sec2hms(timect){

  if(timect=== undefined||timect==0||timect === null){return ''};
  //timect is seconds, NOT milliseconds
  var se=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var mi=timect % 60; //the remainder after div by 60
  timect = Math.floor(timect/60);
  var hr = timect % 24; //the remainder after div by 24
  var dy = Math.floor(timect/24);
  return padify (se, mi, hr, dy);
}

function padify (se, mi, hr, dy){
  hr = hr<10?"0"+hr:hr;
  mi = mi<10?"0"+mi:mi;
  se = se<10?"0"+se:se;
  dy = dy>0?dy+"d ":"";
  return dy+hr+":"+mi+":"+se;
}

Nexus 5 USB driver

Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.

The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.

Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.

Open the System Properties box. Via Command line use sysdm.cpl

** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **

  1. Open the Advanced tab, click Environmental Variables.
  2. Under System Variables, click New.
  3. Enter variable name devmgr_show_nonpresent_devices, under value enter 1.
  4. Restart your computer.

Re-open the Device Manager, under view click Show Hidden Devices.

From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.

ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#

Get parent of current directory from Python script

import os
import sys
from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__)))
print(d)
path1 = os.path.dirname(os.path.realpath(sys.argv[0]))
print(path1)
path = os.path.split(os.path.realpath(__file__))[0]
print(path)

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

How to get current route

to get current router in angular 8 just do this

import {ActivatedRoute} from '@angular/router';

then inject it in constructor like

constructor(private route: ActivatedRoute){}

if you want get current route then use this route.url

if you have multiply name route like /home/pages/list and you wanna access individual then you can access each of like this route.url.value[0].path

value[0] will give home, value[1] will give you pages and value[2] will give you list

Using textures in THREE.js

Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...

  • CoffeeScript

    $(document).ready ->
    
        material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
    
        sphere   = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
    
        $(window).load ->
            renderer.render scene, camera
    
  • JavaScript

    $(document).ready(function() {
    
        material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
    
        sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
    
        $(window).load(function() {
            renderer.render(scene, camera);
        });
    });
    

Thanks...

ie8 var w= window.open() - "Message: Invalid argument."

I discovered the same problem and after reading the first answer that supposed the problem is caused by the window name, changed it : first to '_blank', which worked fine (both compatibility and regular view), then to the previous value, only minus the space in the value :) - also worked. IMO, the problem (or part of it) is caused by IE being unable to use a normal string value as the wname. Hope this helps if anybody runs into the same problem.

Gradle DSL method not found: 'runProguard'

enter image description hereIf you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.

runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System

How to change a css class style through Javascript?

There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).

To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.

Initial Html

<div id="ID"></div>

Setting the class attribute

var div = document.getElementById('ID');
div.className = "foo bar car";

Result:

<div id="ID" class="foo bar car"></div>

Adding a class

div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:

<div id="ID" class="foo bar car tar"></div>

Removing a class

div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:

<div id="ID" class="foo bar"></div>

Checking if a class attribute contains a specific class

if (div.classList.contains("foo")) {
  // Do stuff
}

Toggling a class

var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.

For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.

How to implement "Access-Control-Allow-Origin" header in asp.net

Another option is to add it on the web.config directly:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>

... I found this in here

What is the simplest SQL Query to find the second largest value?

select age from student group by id having age<(select max(age) from student)order by age limit 1

How can I use JSON data to populate the options of a select box?

Take a look at JQuery view engine and just load the array into a dropdown:

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

Xcode 8 shows error that provisioning profile doesn't include signing certificate

This problem is due to private key in the certificate in your profile not match that in your keychain. I resolve this by

  1. delete all iPhone Developer certificate in keychain.
  2. delete all certificate in apple account.
  3. using xcode "Manage Certificates" to add certificate, sometime you still have certificate in your Mac, but I do not know where it is for now, and if added successfully, your apple account will display that certificate too, and then you can create your profile with that certificate and download ... goto 5
  4. if you use "Manage Certificates" can't add certificate, you can create a new certificate, and do remain steps.
  5. finish.

same answer with Code signing issue in Xcode version 8.

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

C programming in Visual Studio

Yes, you very well can learn C using Visual Studio.

Visual Studio comes with its own C compiler, which is actually the C++ compiler. Just use the .c file extension to save your source code.

You don't have to be using the IDE to compile C. You can write the source in Notepad, and compile it in command line using Developer Command Prompt which comes with Visual Studio.

Open the Developer Command Prompt, enter the directory you are working in, use the cl command to compile your C code.

For example, cl helloworld.c compiles a file named helloworld.c.

Refer this for more information: Walkthrough: Compiling a C Program on the Command Line

Hope this helps

Pass parameter from a batch file to a PowerShell script

Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w)
Write-Output $w

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

Parse (split) a string in C++ using string delimiter (standard C++)

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

Example:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token.

Complete Example

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output:

scott
tiger
mushroom

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

Whats the CSS to make something go to the next line in the page?

It depends why the something is on the same line in the first place.

clear in the case of floats, display: block in the case of inline content naturally flowing, nothing will defeat position: absolute as the previous element will be taken out of the normal flow by it.

How to update a single library with Composer?

Just use

composer require {package/packagename}

like

composer require phpmailer/phpmailer

if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.

Replace all occurrences of a string in a data frame

Equivalent to "find and replace." Don't overthink it.

Try it with one:

library(tidyverse)
df <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))

df %>% 
  mutate(var1 = str_replace(var1, " ", ""))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

Apply to all

df %>% 
  mutate_all(funs(str_replace(., " ", "")))
#>   name var1 var2
#> 1    a   <2   <3
#> 2    a   <2   <3
#> 3    a   <2   <3
#> 4    b   <2   <3
#> 5    b   <2   <3
#> 6    b   <2   <3
#> 7    c   <2   <3
#> 8    c   <2   <3
#> 9    c   <2   <3

If the extra space was produced by uniting columns, think about making str_trim part of your workflow.

Created on 2018-03-11 by the reprex package (v0.2.0).

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;

Hibernate openSession() vs getCurrentSession()

SessionFactory: "One SessionFactory per application per DataBase" ( e.g., if you use 3 DataBase's in our application , you need to create sessionFactory object per each DB , totally you need to create 3 sessionFactorys . or else if you have only one DataBase One sessionfactory is enough ).

Session: "One session for one request-response cycle". you can open session when request came and you can close session after completion of request process. Note:-Don't use one session for web application.

Can't bind to 'formGroup' since it isn't a known property of 'form'

The suggested answer did not work for me with Angular 4. Instead I had to use another way of attribute binding with the attr prefix:

<element [attr.attribute-to-bind]="someValue">

Duplicate line in Visual Studio Code

You can use the following depending on your OS:

Windows:

Shift+ Alt + ? or Shift+ Alt + ?

Mac:

Shift + Option + ? or Shift +Option + ?

Linux:

Ctrl+Shift+Alt+? or Ctrl+Shift+Alt+?

Note: For some linux distros use Numpad arrows

use jQuery to get values of selected checkboxes

Map the array is the quickest and cleanest.

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

will return values as an array like:

array => [2,3]

assuming castle and barn were checked and the others were not.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Do not attempt to remove any Apple-supplied system Python which are in /System/Library and /usr/bin, as this may break your whole operating system.


NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.


The complete list is documented here. Basically, all you need to do is the following:

  1. Remove the third-party Python 2.7 framework

    sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
    
  2. Remove the Python 2.7 applications directory

    sudo rm -rf "/Applications/Python 2.7"
    
  3. Remove the symbolic links, in /usr/local/bin, that point to this Python version. See them using

    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' 
    

    and then run the following command to remove all the links:

    cd /usr/local/bin/
    ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
    
  4. If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7 to your PATH environment file. Depending on which shell you use, any of the following files may have been modified: ~/.bash_login, ~/.bash_profile, ~/.cshrc, ~/.profile, ~/.tcshrc, and/or ~/.zprofile.

Sorting rows in a data table

Maybe the following can help:

DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();

Here, you can use other Lambda expression queries too.

CSS file not refreshing in browser

A good way to force your CSS to reload is to:

<link href='styles.css?version=1' rel='stylesheet'></link>

And then just increment the version number as you change your CSS. The browser will then obey. I believe StackOverflow uses this technique.

Dart/Flutter : Converting timestamp

meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.

EDIT:

From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.

import 'package:timeago/timeago.dart' as timeago;

final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));

// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());

// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());

print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes

to convert epochMS to DateTime, just use...

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

Is it possible to use jQuery to read meta tags

Just use something like:

var author = $('meta[name=author]').attr('content');

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

How can I generate Javadoc comments in Eclipse?

For me the /**<NEWLINE> or Shift-Alt-J (or ?-?-J on a Mac) approach works best.

I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.

IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

Remove URL parameters without refreshing page

Better solution :

window.history.pushState(null, null, window.location.pathname);

Recursive sub folder search and return files in a list python

If you don't mind installing an additional light library, you can do this:

pip install plazy

Usage:

import plazy

txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)

The result should look something like this:

['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']

It works on both Python 2.7 and Python 3.

Github: https://github.com/kyzas/plazy#list-files

Disclaimer: I'm an author of plazy.

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

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

Angular/RxJs When should I unsubscribe from `Subscription`

--- Update Angular 9 and Rxjs 6 Solution

  1. Using unsubscribe at ngDestroy lifecycle of Angular Component
class SampleComponent implements OnInit, OnDestroy {
  private subscriptions: Subscription;
  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$.subscribe( ... );
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}
  1. Using takeUntil in Rxjs
class SampleComponent implements OnInit, OnDestroy {
  private unsubscribe$: new Subject<void>;
  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$
    .pipe(takeUntil(this.unsubscribe$))
    .subscribe( ... );
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}
  1. for some action that you call at ngOnInit that just happen only one time when component init.
class SampleComponent implements OnInit {

  private sampleObservable$: Observable<any>;

  constructor () {}

  ngOnInit(){
    this.subscriptions = this.sampleObservable$
    .pipe(take(1))
    .subscribe( ... );
  }
}

We also have async pipe. But, this one use on the template (not in Angular component).

How to get a list column names and datatypes of a table in PostgreSQL?

To make this topic 'more complete'.

I required the column names and data types on a SELECT statement (not a table).

If you want to do this on a SELECT statement instead of an actual existing table, you can do the following:

DROP TABLE IF EXISTS abc;
CREATE TEMPORARY TABLE abc AS
-- your select statement here!
SELECT 
    *
FROM foo
-- end your select statement
;

select column_name, data_type 
from information_schema.columns 
where table_name = 'abc';
DROP IF EXISTS abc;

Short explanation, it makes a (temp) table of your select statement, which you can 'call' upon via the query provided by (among others) @a_horse_with_no_name and @selva.

Hope this helps.

Javascript: Unicode string to hex

how do you get "\u6f22\u5b57" from ?? in JavaScript?

These are JavaScript Unicode escape sequences e.g. \u12AB. To convert them, you could iterate over every code unit in the string, call .toString(16) on it, and go from there.

However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA in the output wherever possible.

Also note that ASCII symbols such as A, b, and - probably don’t need to be escaped.

I’ve written a small JavaScript library that does all this for you, called jsesc. It has lots of options to control the output.

Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97


Your question was tagged as utf-8. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js (online demo).

Find all CSV files in a directory using Python

While solution given by thclpr works it scans only immediate files in the directory and not files in the sub directories if any. Although this is not the requirement but just in case someone wishes to scan sub directories too below is the code that uses os.walk

import os
from glob import glob
PATH = "/home/someuser/projects/someproject"
EXT = "*.csv"
all_csv_files = [file
                 for path, subdir, files in os.walk(PATH)
                 for file in glob(os.path.join(path, EXT))]
print(all_csv_files)

Copied from this blog.

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

Example on ToggleButton

Just remove the line toggle.toggle(); from your click listener toggle() method will always reset your toggle button value.

And as you are trying to take the value of EditText in string variable which always remains same as you are getting value in onCreate() so better directly use the EditText to get the value of it in your onClick listener.

Just change your code as below its working fine now.

  btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                       //toggle.toggle();
            if ( ed.getText().toString().equalsIgnoreCase("1")) {

                toggle.setTextOff("TOGGLE ON");
                toggle.setChecked(true);
            } else if ( ed.getText().toString().equalsIgnoreCase("0")) {

                toggle.setTextOn("TOGGLE OFF");
                toggle.setChecked(false);

            }
        }
    });

How to show all of columns name on pandas dataframe?

you can try this

pd.pandas.set_option('display.max_columns', None)

How can I run Tensorboard on a remote server?

You have to create a ssh connection using port forwarding:

ssh -L 16006:127.0.0.1:6006 user@host

Then you run the tensorboard command:

tensorboard --logdir=/path/to/logs

Then you can easily access the tensorboard in your browser under:

localhost:16006/

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I actually ended up with something like this to allow for the navbar collapse.

@media (min-width: 768px) { //set this to wherever the navbar collapse executes
  .navbar-nav > li > a{
    line-height: 7em; //set this height to the height of the logo.
  }
}

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

How to maximize a plt.show() window using Python

Ok so this is what worked for me. I did the whole showMaximize() option and it does resize your window in proportion to the size of the figure, but it does not expand and 'fit' the canvas. I solved this by:

mng = plt.get_current_fig_manager()                                         
mng.window.showMaximized()
plt.tight_layout()    
plt.savefig('Images/SAVES_PIC_AS_PDF.pdf') 

plt.show()

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

If someone is looking how to represent the GMT as a float number representing hour offset
(for example "GMT-0530" to -5.5), you can use this:

Calendar calendar = new GregorianCalendar();
TimeZone timeZone = calendar.getTimeZone();
int offset = timeZone.getRawOffset();
long hours = TimeUnit.MILLISECONDS.toHours(offset);
float minutes = (float)TimeUnit.MILLISECONDS.toMinutes(offset - TimeUnit.HOURS.toMillis(hours)) / MINUTES_IN_HOUR;
float gmt = hours + minutes;

Change background of LinearLayout in Android

LinearLayout li=(LinearLayout)findViewById(R.id.layoutid);

setting the background color fro ur layout.

li.setBackgroundColor(Color.parseColor("#ffff00"));

this is to set the image which u can store in drawable folder

li.setBackgroundDrawable(drwableItem);

some resource for display purpose animation or img

li.setBackgroundResource(R.id.bckResource);

How to set a default value in react-select

  1. Create a state property for the default option text in the constructor
    • Don't worry about the default option value
  2. Add an option tag to the render function. Only show using state and ternary expression
  3. Create a function to handle when an option was selected
  4. Change the state of the default option value in this event handler function to null

    Class MySelect extends React.Component
    {
        constructor()
        {
            super()
            this.handleChange = this.handleChange.bind(this);
            this.state = {
                selectDefault: "Select An Option"
            }
        }
        handleChange(event)
        {
            const selectedValue = event.target.value;
            //do something with selectedValue
            this.setState({
                selectDefault: null
            });
        }
        render()
        {
            return (
            <select name="selectInput" id="selectInput" onChange={this.handleChange} value= 
                {this.selectedValue}>
             {this.state.selectDefault ? <option>{this.state.selectDefault}</option> : ''}
                {'map list or static list of options here'}
            </select>
            )
        }
    }
    

Correct way to focus an element in Selenium WebDriver using Java

We can also focus webelement using below code:

public focusElement(WebElement element){
    String javaScript = "var evObj = document.createEvent('MouseEvents');"
                    + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
                    + "arguments[0].dispatchEvent(evObj);";

            ((JavascriptExecutor) getDriver()).executeScript(javaScript, element);
}

Hope it helps :)

Custom thread pool in Java 8 parallel stream

There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one.

final int parallelism = 4;
ForkJoinPool forkJoinPool = null;
try {
    forkJoinPool = new ForkJoinPool(parallelism);
    final List<Integer> primes = forkJoinPool.submit(() ->
        // Parallel task here, for example
        IntStream.range(1, 1_000_000).parallel()
                .filter(PrimesPrint::isPrime)
                .boxed().collect(Collectors.toList())
    ).get();
    System.out.println(primes);
} catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
} finally {
    if (forkJoinPool != null) {
        forkJoinPool.shutdown();
    }
}

The trick is based on ForkJoinTask.fork which specifies: "Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool()"

Android Fragment onAttach() deprecated

you are probably using android.support.v4.app.Fragment. For this instead of onAttach method, just use getActivity() to get the FragmentActivity with which the fragment is associated with. Else you could use onAttach(Context context) method.

Not receiving Google OAuth refresh token

In order to get the refresh token you have to add both approval_prompt=force and access_type="offline" If you are using the java client provided by Google it will look like this:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), scopes)
            .build();

AuthorizationCodeRequestUrl authorizationUrl =
            flow.newAuthorizationUrl().setRedirectUri(callBackUrl)
                    .setApprovalPrompt("force")
                    .setAccessType("offline");

JavaScript math, round to two decimal places

To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.



    var testNum = 134.9567654;
    var decPl = 2;
    var testRes = roundDec(testNum,decPl);  
    alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);

    function roundDec(nbr,dec_places){
        var mult = Math.pow(10,dec_places);
        return Math.round(nbr * mult) / mult;
    }

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

Perform Button click event when user press Enter key in Textbox

Put your form inside an asp.net panel control and set its defaultButton attribute with your button Id. See the code below:

  <asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
             </ContentTemplate>
          </asp:UpdatePanel>
    </asp:Panel>

Hope this will help you...

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

Sending commands and strings to Terminal.app with Applescript

Here's another way, but with the advantage that it launches Terminal, brings it to the front, and creates only one window.

I like this when I want to be neatly presented with the results of my script.

tell application "Terminal"
    activate
    set shell to do script "echo 1" in window 1
    do script "echo 2" in shell
    do script "echo 3" in shell
end tell

Date / Timestamp to record when a record was added to the table?

You can use a datetime field and set it's default value to GetDate().

CREATE TABLE [dbo].[Test](
    [TimeStamp] [datetime] NOT NULL CONSTRAINT [DF_Test_TimeStamp] DEFAULT (GetDate()),
    [Foo] [varchar](50) NOT NULL
) ON [PRIMARY]

How to install plugins to Sublime Text 2 editor?

You need to install Package Control first (from the Python console in Sublime. Visit http://wbond.net/sublime_packages/package_control for more info), and then install emmet from their repository.

jquery - Check for file extension before uploading

You can achieve this using JQuery

HTML

 <input type="file" id="FilUploader" />

JQuery

    $("#FilUploader").change(function () {
        var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
            alert("Only formats are allowed : "+fileExtension.join(', '));
        }
    });

For more info Click Here

How do I get the Back Button to work with an AngularJS ui-router state machine?

Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.

Directive usage

<a data-go-back-history>Previous State</a>

Angular directive declaration

.directive('goBackHistory', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            elm.on('click', function ($event) {
                $event.stopPropagation();
                if ($window.history.length) {
                    $window.history.back();
                } else {
                    $window.close();  
                }
            });
        }
    };
}])

Note: Working using ui-router or not.

How to find index of list item in Swift?

Swift 2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

Swift 3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

How to add Options Menu to Fragment in Android

Setting the options menu after creating the fragment view worked well for me.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);        
}

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

Can someone post a well formed crossdomain.xml sample?

Take a look at Twitter's:

http://twitter.com/crossdomain.xml

<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
    <allow-access-from domain="twitter.com" />
    <allow-access-from domain="api.twitter.com" />
    <allow-access-from domain="search.twitter.com" />
    <allow-access-from domain="static.twitter.com" />
    <site-control permitted-cross-domain-policies="master-only"/>
    <allow-http-request-headers-from domain="*.twitter.com" headers="*" secure="true"/>
</cross-domain-policy>

Colon (:) in Python list index

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

Create directory if it does not exist

Use:

$path = "C:\temp\"

If (!(test-path $path))
{
    md C:\Temp\
}
  • The first line creates a variable named $path and assigns it the string value of "C:\temp\"

  • The second line is an If statement which relies on the Test-Path cmdlet to check if the variable $path does not exist. The not exists is qualified using the ! symbol.

  • Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.

md is the short version of typing out: New-Item -ItemType Directory -Path $path

Note: I have not tested using the -Force parameter with the below to see if there is undesirable behavior if the path already exists.

New-Item -ItemType Directory -Path $path

Are there such things as variables within an Excel formula?

Yes. But not directly.

Simpler way

  • You could post Vlookup() in one cell and use its address in where required. - This is perhaps the only direct way of using variables in Excel.

OR

  • You could define Vlookup(reference)-10 as a wrapper function from within VBE Macros. Press Alt+f12 and use that function

Mockito - NullpointerException when stubbing Method

As this is the closest I found to the issue I had, it's the first result that comes up and I didn't find an appropriate answer, I'll post the solution here for any future poor souls:

any() doesn't work where mocked class method uses a primitive parameter.

 public Boolean getResult(String identifier, boolean switch)

The above will produce the same exact issue as OP.

Solution, just wrap it:

 public Boolean getResult(String identifier, Boolean switch)

The latter solves the NPE.

unique() for more than one variable

There are a few ways to get all unique combinations of a set of factors.

with(df, interaction(yad, per, drop=TRUE))   # gives labels
with(df, yad:per)                            # ditto

aggregate(numeric(nrow(df)), df[c("yad", "per")], length)    # gives a data frame

Get all object attributes in Python?

I use __dict__

Example:

class MyObj(object):
  def __init__(self):
    self.name = 'Chuck Norris'
    self.phone = '+6661'

obj = MyObj()
print(obj.__dict__)

# Output:  
# {'phone': '+6661', 'name': 'Chuck Norris'}

Proper way to make HTML nested list?

Option 2 is correct: The nested <ul> is a child of the <li> it belongs in.

If you validate, option 1 comes up as an error in html 5 -- credit: user3272456


Correct: <ul> as child of <li>

The proper way to make HTML nested list is with the nested <ul> as a child of the <li> to which it belongs. The nested list should be inside of the <li> element of the list in which it is nested.

<ul>
    <li>Parent/Item
        <ul>
            <li>Child/Subitem
            </li>
        </ul>
    </li>
</ul>

W3C Standard for Nesting Lists

A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:

  1. Chapter One
    1. Section One
    2. Section Two
    3. Section Three
  2. Chapter Two
  3. Chapter Three

The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:

<ol>
  <li>Chapter One
    <ol>
      <li>Section One</li>
      <li>Section Two </li>
      <li>Section Three </li>
    </ol>
  </li>
  <li>Chapter Two</li>
  <li>Chapter Three  </li>
</ol>

Note how the nested list starts after the <li> and the text of the containing list item (“Chapter One”); then ends before the </li> of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.

Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

check forthe followings :

Make sure your database engine is configured to accept remote connections

• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration • Click on Surface Area Configuration for Services and Connections • Select the instance that is having a problem > Database Engine > Remote Connections • Enable local and remote connections • Restart instance

  1. Check the SQL Server service account

• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding

  1. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb P.NET application

• Usually the format needed to specify the database server is machinename\instancename • Check your connection string as well

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How to copy data to clipboard in C#

Clipboard.SetText("hello");

You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

Reshape an array in NumPy

There are two possible result rearrangements (following example by @eumiro). Einops package provides a powerful notation to describe such operations non-ambigously

>> a = np.arange(18).reshape(9,2)

# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)

array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)

array([[[ 0,  2,  4],
        [ 6,  8, 10],
        [12, 14, 16]],

       [[ 1,  3,  5],
        [ 7,  9, 11],
        [13, 15, 17]]])

How can I remove a commit on GitHub?

In case you like to keep the commit changes after deletion:

Note that this solution works if the commit to be removed is the last committed one.


1 - Copy the commit reference you like to go back to from the log:

git log

2 - Reset git to the commit reference:

 git reset <commit_ref>

3 - Stash/store the local changes from the wrong commit to use later after pushing to remote:

 git stash

4 - Push the changes to remote repository, (-f or --force):

git push -f

5 - Get back the stored changes to local repository:

git stash apply

7 - In case you have untracked/new files in the changes, you need to add them to git before committing:

git add .

6 - Add whatever extra changes you need, then commit the needed files, (or use a dot '.' instead of stating each file name, to commit all files in the local repository:

git commit -m "<new_commit_message>" <file1> <file2> ...

or

git commit -m "<new_commit_message>" .

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

How do you run a single query through mysql from the command line?

mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"

From the usage printout:

-e, --execute=name
Execute command and quit. (Disables --force and history file)

Combine Multiple child rows into one row MYSQL

If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):

Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value

FROM Ordered_Items OI
    LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID
    LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID
    LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID
    LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID

GROUP BY OI.ID, OI.Item_Name

The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.

Accessing JPEG EXIF rotation data in JavaScript on the client side

You can use the exif-js library in combination with the HTML5 File API: http://jsfiddle.net/xQnMd/1/.

$("input").change(function() {
    var file = this.files[0];  // file
        fr   = new FileReader; // to read file contents

    fr.onloadend = function() {
        // get EXIF data
        var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));

        // alert a value
        alert(exif.Make);
    };

    fr.readAsBinaryString(file); // read the file
});

Delete newline in Vim

I would just press A (append to end of line, puts you into insert mode) on the line where you want to remove the newline and then press delete.

Detect touch press vs long press vs movement?

This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).

private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;

@Override
public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mDownX = ev.getX();
            mDownY = ev.getY();
            isOnClick = true;
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            if (isOnClick) {
                Log.i(LOG_TAG, "onClick ");
                //TODO onClick code
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
                Log.i(LOG_TAG, "movement detected");
                isOnClick = false;
            }
            break;
        default:
            break;
    }
    return true;
}

For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:

Detecting a long press with Android

How to unzip a file using the command line?

7-Zip, it's open source, free and supports a wide range of formats.

7z.exe x myarchive.zip

How to format font style and color in echo

 echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";

Interface defining a constructor signature?

One way to solve this problem is to leverage generics and the new() constraint.

Instead of expressing your constructor as a method/function, you can express it as a factory class/interface. If you specify the new() generic constraint on every call site that needs to create an object of your class, you will be able to pass constructor arguments accordingly.

For your IDrawable example:

public interface IDrawable
{
    void Update();
    void Draw();
}

public interface IDrawableConstructor<T> where T : IDrawable
{
    T Construct(GraphicsDeviceManager manager);
}


public class Triangle : IDrawable
{
    public GraphicsDeviceManager Manager { get; set; }
    public void Draw() { ... }
    public void Update() { ... }
    public Triangle(GraphicsDeviceManager manager)
    {
        Manager = manager;
    }
}


public TriangleConstructor : IDrawableConstructor<Triangle>
{
    public Triangle Construct(GraphicsDeviceManager manager)
    {
        return new Triangle(manager);
    } 
}

Now when you use it:

public void SomeMethod<TBuilder>(GraphicsDeviceManager manager)
  where TBuilder: IDrawableConstructor<Triangle>, new()
{
    // If we need to create a triangle
    Triangle triangle = new TBuilder().Construct(manager);

    // Do whatever with triangle
}

You can even concentrate all creation methods in a single class using explicit interface implementation:

public DrawableConstructor : IDrawableConstructor<Triangle>,
                             IDrawableConstructor<Square>,
                             IDrawableConstructor<Circle>
{
    Triangle IDrawableConstructor<Triangle>.Construct(GraphicsDeviceManager manager)
    {
        return new Triangle(manager);
    } 

    Square IDrawableConstructor<Square>.Construct(GraphicsDeviceManager manager)
    {
        return new Square(manager);
    } 

    Circle IDrawableConstructor<Circle>.Construct(GraphicsDeviceManager manager)
    {
        return new Circle(manager);
    } 
}

To use it:

public void SomeMethod<TBuilder, TShape>(GraphicsDeviceManager manager)
  where TBuilder: IDrawableConstructor<TShape>, new()
{
    // If we need to create an arbitrary shape
    TShape shape = new TBuilder().Construct(manager);

    // Do whatever with the shape
}

Another way is by using lambda expressions as initializers. At some point early in the call hierarchy, you will know which objects you will need to instantiate (i.e. when you are creating or getting a reference to your GraphicsDeviceManager object). As soon as you have it, pass the lambda

() => new Triangle(manager) 

to subsequent methods so they will know how to create a Triangle from then on. If you can't determine all possible methods that you will need, you can always create a dictionary of types that implement IDrawable using reflection and register the lambda expression shown above in a dictionary that you can either store in a shared location or pass along to further function calls.

grep --ignore-case --only

I'd suggest that the -i means it does match "ABC", but the difference is in the output. -i doesn't manipulate the input, so it won't change "ABC" to "abc" because you specified "abc" as the pattern. -o says it only shows the part of the output that matches the pattern specified, it doesn't say about matching input.

The output of echo "ABC" | grep -i abc is ABC, the -o shows output matching "abc" so nothing shows:

Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o abc
Naos:~ mattlacey$ echo "ABC" | grep -i abc | grep -o ABC
ABC

typeof !== "undefined" vs. != null

You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:

(function($, Backbone, _, undefined) {
    //undefined is undefined here.
})(jQuery, Backbone, _);

If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:

if(window.neverDefined === undefined) {
    //Code works
}

Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.

On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.

Add left/right horizontal padding to UILabel

UIView* bg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 70)];
bg.backgroundColor = [UIColor blackColor];
UILabel* yourLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, y, yourWidth, yourHeight)];
[bg addSubview:yourLabel];

[self addSubview:bg];

How to stop docker under Linux

if you have no systemctl and started the docker daemon by:

sudo service docker start

you can stop it by:

sudo service docker stop

EntityType has no key defined error

For me, the model was fine. It was because I had 2 different versions of entity framework. One version for the web project and another one for the common project which contains the models.

I just had to consolidate the nuget packages.

enter image description here

Enjoy!

HTML.HiddenFor value set

For setting value in hidden field do in the following way:

@Html.HiddenFor(model => model.title, 
                new { id= "natureOfVisitField", Value = @Model.title})

It will work

Provide an image for WhatsApp link sharing

I documented the perfect detailed solution here - https://amprandom.blogspot.com/2016/12/blogger-whatsapp-rich-link-preview.html There are seven steps to be done to get the perfect preview.

Title : Add Keyword rich title to your webpage with maximum of 65 characters.

Meta Description : Describe your web page in a maximum of 155 characters.

og:title : Maximum 35 characters.

og:url : Full link to your webpage address.

og:description : Maximum 65 characters.

og:image : Image(JPG or PNG) of size less than 300KB and minimum dimension of 300 x 200 pixel is advised.

favicon : A small icon of dimensions 32 x 32 pixels.

In the above page, you have the required specifications, the character limit and sample tags. Do upvote once you find it satisfactory.

How might I convert a double to the nearest integer value?

Methods in other answers throw OverflowException if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_

int result = 0;
try {
    result = Convert.ToInt32(value);
}
catch (OverflowException) {
    if (value > 0) result = int.MaxValue;
    else result = int.Minvalue;
}

Install Android App Bundle on device

Installing the aab directly from the device, I couldn't find a way for that.

But there is a way to install it through your command line using the following documentation You can install apk to a device through BundleTool

According to "@Albert Vila Calvo" comment he noted that to install bundletools using HomeBrew use brew install bundletool

You can now install extract apks from aab file and install it to a device

Extracting apk files from through the next command

java -jar bundletool-all-0.3.3.jar build-apks --bundle=bundle.aab --output=app.apks --ks=my-release-key.keystore --ks-key-alias=alias --ks-pass=pass:password

Arguments:

  • --bundle -> Android Bundle .aab file
  • --output -> Destination and file name for the generated apk file
  • --ks -> Keystore file used to generate the Android Bundle
  • --ks-key-alias -> Alias for keystore file
  • --ks-pass -> Password for Alias file (Please note the 'pass' prefix before password value)

Then you will have a file with extension .apks So now you need to install it to a device

java -jar bundletool-all-0.6.0.jar install-apks --adb=/android-sdk/platform-tools/adb --apks=app.apks

Arguments:

  • --adb -> Path to adb file
  • --apks -> Apks file need to be installed

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

ASP.NET 2.0 - How to use app_offline.htm

I have used the extremely handy app_offline.htm trick to shut down/update sites in the past without any issues.

Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.

Also ensure that the file is named exactly as it should be: app_offline.htm

Other than that, there should be no other changes to IIS that you should need to make since the processing of this file (with this specific name) is handled by the ASP.NET runtime rather than IIS itself (for IIS v6).

Be aware, however, that although placing this file in the root of your site will force the application to "shut down" and display the content of the "app_offline.htm" file itself, any existing requests will still get the real website served up to them. Only new requests will get the app_offline.htm content.

If you're still having issues, try the following links for further info:

Scott Gu's App_Offline.htm

App_Offline.htm and working around the "IE Friendly Errors" feature

Will app_offline.htm stop current requests or just new requests?

Laravel: Auth::user()->id trying to get a property of a non-object

It's working with me :

echo Auth::guard('guard_name')->user()->id;

Using Oracle to_date function for date string with milliseconds

TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.

Hope that helps.

How can I convert an integer to a hexadecimal string in C?

This code

int a = 5;
printf("%x\n", a);

prints

5

This code

int a = 5; 
printf("0x%x\n", a);

prints

0x5

This code

int a = 89778116;
printf("%x\n", a);

prints

559e7c4

If you capitalize the x in the format it capitalizes the hex value:

int a = 89778116;
printf("%X\n", a);

prints

559E7C4

If you want to print pointers you use the p format specifier:

char* str = "foo";
printf("0x%p\n", str);

prints

0x01275744

Is there any way to configure multiple registries in a single npmrc file

My approach was to make a slight command line variant that adds the registry switch.

I created these files in the nodejs folder where the npm executable is found:

npm-.cmd:

@ECHO OFF
npm --registry https://registry.npmjs.org %*

npm-:

#!/bin/sh
"npm" --registry https://registry.npmjs.org "$@"

Now, if I want to do an operation against the normal npm registry (while I am not connected to the VPN), I just type npm- where I would usually type npm.

To test this command and see the registry for a package, use this example:

npm- view lodash

PS. I am in windows and have tested this in Bash, CMD, and Powershell. I also

Spring @PropertySource using YAML

<dependency>
  <groupId>com.github.yingzhuo</groupId>
  <artifactId>spring-boot-stater-env</artifactId>
  <version>0.0.3</version>
</dependency>

Welcome to use my library. Now yaml, toml, hocon is supported.

Source: github.com

Create Excel files from C# without office

An interop calls something else, it's an interoperability assembly, so you're inter-operating with something...in this case Excel, the actual installed Excel.

In this case yes, it will fail to run because it depends on excel, you're just calling excel functions. If they don't have it installed...out of luck.

There are methods to generate without Excel, provided the 2007 file format is ok, here's a few:

as I said though, this is the 2007 format, normally if anything, that's the deal-breaker.

URLEncoder not able to translate space character

Hello+World is how a browser will encode form data (application/x-www-form-urlencoded) for a GET request and this is the generally accepted form for the query part of a URI.

http://host/path/?message=Hello+World

If you sent this request to a Java servlet, the servlet would correctly decode the parameter value. Usually the only time there are issues here is if the encoding doesn't match.

Strictly speaking, there is no requirement in the HTTP or URI specs that the query part to be encoded using application/x-www-form-urlencoded key-value pairs; the query part just needs to be in the form the web server accepts. In practice, this is unlikely to be an issue.

It would generally be incorrect to use this encoding for other parts of the URI (the path for example). In that case, you should use the encoding scheme as described in RFC 3986.

http://host/Hello%20World

More here.

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Kinda late, but you need to access the original event, not the jQuery massaged one. Also, since these are multi-touch events, other changes need to be made:

$('#box').live('touchstart', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

If you want other fingers, you can find them in other indices of the touches list.

UPDATE FOR NEWER JQUERY:

$(document).on('touchstart', '#box', function(e) {
  var xPos = e.originalEvent.touches[0].pageX;
});

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

I had this problem on Windows 7. My situation is this through SDK Manager. I only download API 19 but I had not downloaded related Android SDK build-tools. So it occur this problem.

I went through SDK Manager download build-tools 19 to fix it. Hope to give you help.

`export const` vs. `export default` in ES6

export default affects the syntax when importing the exported "thing", when allowing to import, whatever has been exported, by choosing the name in the import itself, no matter what was the name when it was exported, simply because it's marked as the "default".

A useful use case, which I like (and use), is allowing to export an anonymous function without explicitly having to name it, and only when that function is imported, it must be given a name:


Example:

Export 2 functions, one is default:

export function divide( x ){
    return x / 2;
}

// only one 'default' function may be exported and the rest (above) must be named
export default function( x ){  // <---- declared as a default function
    return x * x;
}

Import the above functions. Making up a name for the default one:

// The default function should be the first to import (and named whatever)
import square, {divide} from './module_1.js'; // I named the default "square" 

console.log( square(2), divide(2) ); // 4, 1

When the {} syntax is used to import a function (or variable) it means that whatever is imported was already named when exported, so one must import it by the exact same name, or else the import wouldn't work.


Erroneous Examples:

  1. The default function must be first to import

    import {divide}, square from './module_1.js
    
  2. divide_1 was not exported in module_1.js, thus nothing will be imported

    import {divide_1} from './module_1.js
    
  3. square was not exported in module_1.js, because {} tells the engine to explicitly search for named exports only.

    import {square} from './module_1.js
    

Using varchar(MAX) vs TEXT on SQL Server

  • Basic Definition

TEXT and VarChar(MAX) are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).

  • Which one to Use?

As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.

  • In-Row or Out-of-Row Storage

Data of a Text type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max) type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row Varchar(Max) is good for searches and retrieval.

  • Supported/Unsupported Functionalities

Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.

  1. = Equal to Operator on VarChar(Max) type column
  2. Group by clause on VarChar(Max) type column

    • System IO Considerations

As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.

But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.

Conclusion

Use VarChar(MAX) data type rather than TEXT for good performance.

Source