Programs & Examples On #Gilead

Gilead was previously known as hibernate4gwt : the library has been renamed to reflect a more general purpose than just these two target frameworks, but of course, it still supports them.

iPhone - Grand Central Dispatch main thread

Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.

For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.

If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

Cross origin requests are only supported for HTTP but it's not cross-domain

I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.

  1. Install express npm install express

  2. Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server

  3. Put something like the following in the server.js file and read about this on the express gihub site:

    var express = require('express');
    var app = express();
    var path = require('path');
    
    // __dirname will use the current path from where you run this file 
    app.use(express.static(__dirname));
    app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
    
    app.listen(8000);
    console.log('Listening on port 8000');
    
  4. After you've saved server.js, you can run the server using:

node server.js

  1. Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load

Session 'app' error while installing APK

In my case, my project location contained the special character.

E:\Android_Projects\T&PUIET,KUK\app\build\outputs\apk\app-debug.apk

close android studio > rename folder containing the special character(here T&PUIET,KUK ) > restart android studio.

Hope this Solution helps!

Copying Code from Inspect Element in Google Chrome

You can copy by inspect element and target the div you want to copy. Just press ctrl+c and then your div will be copy and paste in your code it will run easily.

Return a "NULL" object if search result not found

The reason that you can't return NULL here is because you've declared your return type as Attr&. The trailing & makes the return value a "reference", which is basically a guaranteed-not-to-be-null pointer to an existing object. If you want to be able to return null, change Attr& to Attr*.

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

How to get the second column from command output?

If you have GNU awk this is the solution you want:

$ awk '{print $1}' FPAT='"[^"]+"' file
"A B"
"C"
"D"

How to Add Stacktrace or debug Option when Building Android Studio Project

To Increase Maximum heap: Click to open your Android Studio, look at below pictures. Step by step. ANDROID STUDIO v2.1.2

Click to navigate to Settings from the Configure or GO TO FILE SETTINGS at the top of Android Studio.

enter image description here

check also the android compilers from the link to confirm if it also change if not increase to the same size you modify from the compiler link.

Note: You can increase the size base on your memory capacity and remember this setting is base on Android Studio v2.1.2

Prevent Default on Form Submit jQuery

Try this:

$("#cpa-form").submit(function(e){
    return false;
});

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

"Rate This App"-link in Google Play store app on the phone

In-App Review API is a long-awaited feature that Google has launched in August 2020 like Apple did in 2016 for iOS apps.

With this API users will review and rate an application without leaving it. Google suggestion to developers not to force users to rate or review all the time as this API allocate a quota to each user on the specific usage of the application in a time. Surely developers would not be able to interrupt users with an attractive pop-up in the middle of their task.

Java

In Application level (build.gradle)

       dependencies {
            // This dependency from the Google Maven repository.
            // include that repository in your project's build.gradle file.
            implementation 'com.google.android.play:core:1.9.0'
        }

 

boolean isGMSAvailable = false;
int result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
isGMSAvailable = (com.google.android.gms.common.ConnectionResult.SUCCESS == result);
  if(isGMSAvailable)
  {
    ReviewManager manager = ReviewManagerFactory.create(this);
    Task<ReviewInfo> request = manager.requestReviewFlow();
    request.addOnCompleteListener(task -> {
      try {
        if (task.isSuccessful())
        {
           // getting ReviewInfo object
            ReviewInfo reviewInfo = task.getResult();
            Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);
            flow.addOnCompleteListener(task2 -> {
                // The flow has finished. The API does not indicate whether the user
                // reviewed or not, or even whether the review dialog was shown. Thus,
                // no matter the result, we continue our app flow.
                   });
        } else 
        {
            // There was some problem, continue regardless of the result
           // call old method for rating and user will land in Play Store App page
           Utils.rateOnPlayStore(this);       
        }
        } catch (Exception ex)
        {
            Log.e("review Ex", "review & rate: "+ ex);
                 }
                });
    }
    else
    {
       // if user has not installed Google play services in his/her device you land them to 
       // specific store e.g. Huawei AppGallery or Samsung Galaxy Store 
       Utils.rateOnOtherStore(this);
    }   

Kotlin

val manager = ReviewManagerFactory.create(context)
val request = manager.requestReviewFlow()
request.addOnCompleteListener { request ->
    if (request.isSuccessful) {
        // We got the ReviewInfo object
        val reviewInfo = request.result
    } else {
        // There was some problem, continue regardless of the result.
    }
}

//Launch the in-app review flow

val flow = manager.launchReviewFlow(activity, reviewInfo)
flow.addOnCompleteListener { _ ->
    // The flow has finished. The API does not indicate whether the user
    // reviewed or not, or even whether the review dialog was shown. Thus, no
    // matter the result, we continue our app flow.
}

for Testing use FakeReviewManager

//java
ReviewManager manager = new FakeReviewManager(this);

//Kotlin
val manager = FakeReviewManager(context)

Duplicate AssemblyVersion Attribute

This issue is a reference conflict which is mostly peculiar to VS 2017.

I solved this same error by simply commenting out lines 7 -14 as well as Assembly version codes at the bottom of the page on AssemblyInfo.cs

It removed all the duplicate references and the project was able to build again.

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

Can I escape html special chars in javascript?

Came across this issue when building a DOM structure. This question helped me solve it. I wanted to use a double chevron as a path separator, but appending a new text node directly resulted in the escaped character code showing, rather than the character itself:

var _div = document.createElement('div');
var _separator = document.createTextNode('&raquo;');
//_div.appendChild(_separator); /* this resulted in '&raquo;' being displayed */
_div.innerHTML = _separator.textContent; /* this was key */

How to initialize var?

Thank you Mr.Snake, Found this helpfull for another trick i was looking for :) (Not enough rep to comment)

Shorthand assignment of nullable types. Like this:

var someDate = !Convert.IsDBNull(dataRow["SomeDate"])
                    ? Convert.ToDateTime(dataRow["SomeDate"])
                    : (DateTime?) null;

Using context in a fragment

Inside fragment for kotlin sample would help someone

textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

if you use databinding;

bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

Where bindingView is initialized in onCreateView like this

private lateinit var bindingView: FragmentBookingHistoryDetailBinding

bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)

How to set HTTP headers (for cache-control)?

You can set the headers in PHP by using:

<?php
  //set headers to NOT cache a page
  header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
  header("Pragma: no-cache"); //HTTP 1.0
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

  //or, if you DO want a file to cache, use:
  header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)

?>

Note that the exact headers used will depend on your needs (and if you need to support HTTP 1.0 and/or HTTP 1.1)

Prefer composition over inheritance?

Even though Composition is preferred, I would like to highlight pros of Inheritance and cons of Composition.

Pros of Inheritance:

  1. It establishes a logical "IS A" relation. If Car and Truck are two types of Vehicle ( base class), child class IS A base class.

    i.e.

    Car is a Vehicle

    Truck is a Vehicle

  2. With inheritance, you can define/modify/extend a capability

    1. Base class provides no implementation and sub-class has to override complete method (abstract) => You can implement a contract
    2. Base class provides default implementation and sub-class can change the behaviour => You can re-define contract
    3. Sub-class adds extension to base class implementation by calling super.methodName() as first statement => You can extend a contract
    4. Base class defines structure of the algorithm and sub-class will override a part of algorithm => You can implement Template_method without change in base class skeleton

Cons of Composition:

  1. In inheritance, subclass can directly invoke base class method even though it's not implementing base class method because of IS A relation. If you use composition, you have to add methods in container class to expose contained class API

e.g. If Car contains Vehicle and if you have to get price of the Car, which has been defined in Vehicle, your code will be like this

class Vehicle{
     protected double getPrice(){
          // return price
     }
} 

class Car{
     Vehicle vehicle;
     protected double getPrice(){
          return vehicle.getPrice();
     }
} 

How do I compute derivative using Numpy?

Assuming you want to use numpy, you can numerically compute the derivative of a function at any point using the Rigorous definition:

def d_fun(x):
    h = 1e-5 #in theory h is an infinitesimal
    return (fun(x+h)-fun(x))/h

You can also use the Symmetric derivative for better results:

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Using your example, the full code should look something like:

def fun(x):
    return x**2 + 1

def d_fun(x):
    h = 1e-5
    return (fun(x+h)-fun(x-h))/(2*h)

Now, you can numerically find the derivative at x=5:

In [1]: d_fun(5)
Out[1]: 9.999999999621423

Java method: Finding object in array list given a known attribute value

I solved this using java 8 lambdas

int dogId = 2;

return dogList.stream().filter(dog-> dogId == dog.getId()).collect(Collectors.toList()).get(0);

How are environment variables used in Jenkins with Windows Batch Command?

I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.

If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE

echo %WORKSPACE%

If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &, &&, or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.

setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
  set WORKSPACE=AFTER
  echo Normal Expansion = %WORKSPACE%
  echo Delayed Expansion = !WORKSPACE!
)

The output of the above is

Normal Expansion = BEFORE
Delayed Expansion = AFTER

Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.

What is the best way to detect a mobile device?

All answers use user-agent to detect the browser but device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).

To detect mobile you can check for touch events:

function is_touch_device() {
  return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}

Taken from What's the best way to detect a 'touch screen' device using JavaScript?

How to send a simple email from a Windows batch file?

I've used Blat ( http://www.blat.net/ ) for many years. It's a simple command line utility that can send email from command line. It's free and opensource.

You can use command like "Blat myfile.txt -to [email protected] -server smtp.domain.com -port 6000"

Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm

Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software

The following VBScript code is taken from that page

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "[email protected]"
objEmail.To = "[email protected]"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send

Save the file as something.vbs

Set Msg = CreateObject("CDO.Message")

With Msg

 .To = "[email protected]"
 .From = "[email protected]"
 .Subject = "Hello"
 .TextBody = "Just wanted to say hi."
 .Send

End With

Save the file as something2.vbs

I think these VBS scripts use the windows default mail server, if present. I've not tested these scripts...

What encoding/code page is cmd.exe using?

I've been frustrated for long by Windows code page issues, and the C programs portability and localisation issues they cause. The previous posts have detailed the issues at length, so I'm not going to add anything in this respect.

To make a long story short, eventually I ended up writing my own UTF-8 compatibility library layer over the Visual C++ standard C library. Basically this library ensures that a standard C program works right, in any code page, using UTF-8 internally.

This library, called MsvcLibX, is available as open source at https://github.com/JFLarvoire/SysToolsLib. Main features:

  • C sources encoded in UTF-8, using normal char[] C strings, and standard C library APIs.
  • In any code page, everything is processed internally as UTF-8 in your code, including the main() routine argv[], with standard input and output automatically converted to the right code page.
  • All stdio.h file functions support UTF-8 pathnames > 260 characters, up to 64 KBytes actually.
  • The same sources can compile and link successfully in Windows using Visual C++ and MsvcLibX and Visual C++ C library, and in Linux using gcc and Linux standard C library, with no need for #ifdef ... #endif blocks.
  • Adds include files common in Linux, but missing in Visual C++. Ex: unistd.h
  • Adds missing functions, like those for directory I/O, symbolic link management, etc, all with UTF-8 support of course :-).

More details in the MsvcLibX README on GitHub, including how to build the library and use it in your own programs.

The release section in the above GitHub repository provides several programs using this MsvcLibX library, that will show its capabilities. Ex: Try my which.exe tool with directories with non-ASCII names in the PATH, searching for programs with non-ASCII names, and changing code pages.

Another useful tool there is the conv.exe program. This program can easily convert a data stream from any code page to any other. Its default is input in the Windows code page, and output in the current console code page. This allows to correctly view data generated by Windows GUI apps (ex: Notepad) in a command console, with a simple command like: type WINFILE.txt | conv

This MsvcLibX library is by no means complete, and contributions for improving it are welcome!

How to center align the cells of a UICollectionView?

Here is how you can do it and it works fine

func refreshCollectionView(_ count: Int) {
    let collectionViewHeight = collectionView.bounds.height
    let collectionViewWidth = collectionView.bounds.width
    let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
    if numberOfItemsThatCanInCollectionView > count {
        let totalCellWidth = collectionViewHeight * CGFloat(count)
        let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
        // leftInset, rightInset are the global variables which I am passing to the below function
        leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        rightInset = -leftInset
    } else {
        leftInset = 0.0
        rightInset = -collectionViewHeight
    }
    collectionView.reloadData()
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}

Can Linux apps be run in Android?

yes you can ;-)

the simplest way is using this ->http://www.androidfanatic.com/community-forums.html?func=view&catid=9&id=2248

The old link is dead it was for a Debian install script There is an app for that in the android market but you will need root

How to store token in Local or Session Storage in Angular 2?

Simple example:

var userID = data.id;

localStorage.setItem('userID',JSON.stringify(userID));

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

Can I embed a .png image into an html page?

There are a few base64 encoders online to help you with this, this is probably the best I've seen:

http://www.greywyvern.com/code/php/binary2base64

As that page shows your main options for this are CSS:

div.image {
  width:100px;
  height:100px;
  background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>); 
}

Or the <img> tag itself, like this:

<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />

What does T&& (double ampersand) mean in C++11?

It declares an rvalue reference (standards proposal doc).

Here's an introduction to rvalue references.

Here's a fantastic in-depth look at rvalue references by one of Microsoft's standard library developers.

CAUTION: the linked article on MSDN ("Rvalue References: C++0x Features in VC10, Part 2") is a very clear introduction to Rvalue references, but makes statements about Rvalue references that were once true in the draft C++11 standard, but are not true for the final one! Specifically, it says at various points that rvalue references can bind to lvalues, which was once true, but was changed.(e.g. int x; int &&rrx = x; no longer compiles in GCC) – drewbarbs Jul 13 '14 at 16:12

The biggest difference between a C++03 reference (now called an lvalue reference in C++11) is that it can bind to an rvalue like a temporary without having to be const. Thus, this syntax is now legal:

T&& r = T();

rvalue references primarily provide for the following:

Move semantics. A move constructor and move assignment operator can now be defined that takes an rvalue reference instead of the usual const-lvalue reference. A move functions like a copy, except it is not obliged to keep the source unchanged; in fact, it usually modifies the source such that it no longer owns the moved resources. This is great for eliminating extraneous copies, especially in standard library implementations.

For example, a copy constructor might look like this:

foo(foo const& other)
{
    this->length = other.length;
    this->ptr = new int[other.length];
    copy(other.ptr, other.ptr + other.length, this->ptr);
}

If this constructor was passed a temporary, the copy would be unnecessary because we know the temporary will just be destroyed; why not make use of the resources the temporary already allocated? In C++03, there's no way to prevent the copy as we cannot determine we were passed a temporary. In C++11, we can overload a move constructor:

foo(foo&& other)
{
   this->length = other.length;
   this->ptr = other.ptr;
   other.length = 0;
   other.ptr = nullptr;
}

Notice the big difference here: the move constructor actually modifies its argument. This would effectively "move" the temporary into the object being constructed, thereby eliminating the unnecessary copy.

The move constructor would be used for temporaries and for non-const lvalue references that are explicitly converted to rvalue references using the std::move function (it just performs the conversion). The following code both invoke the move constructor for f1 and f2:

foo f1((foo())); // Move a temporary into f1; temporary becomes "empty"
foo f2 = std::move(f1); // Move f1 into f2; f1 is now "empty"

Perfect forwarding. rvalue references allow us to properly forward arguments for templated functions. Take for example this factory function:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1& a1)
{
    return std::unique_ptr<T>(new T(a1));
}

If we called factory<foo>(5), the argument will be deduced to be int&, which will not bind to a literal 5, even if foo's constructor takes an int. Well, we could instead use A1 const&, but what if foo takes the constructor argument by non-const reference? To make a truly generic factory function, we would have to overload factory on A1& and on A1 const&. That might be fine if factory takes 1 parameter type, but each additional parameter type would multiply the necessary overload set by 2. That's very quickly unmaintainable.

rvalue references fix this problem by allowing the standard library to define a std::forward function that can properly forward lvalue/rvalue references. For more information about how std::forward works, see this excellent answer.

This enables us to define the factory function like this:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1&& a1)
{
    return std::unique_ptr<T>(new T(std::forward<A1>(a1)));
}

Now the argument's rvalue/lvalue-ness is preserved when passed to T's constructor. That means that if factory is called with an rvalue, T's constructor is called with an rvalue. If factory is called with an lvalue, T's constructor is called with an lvalue. The improved factory function works because of one special rule:

When the function parameter type is of the form T&& where T is a template parameter, and the function argument is an lvalue of type A, the type A& is used for template argument deduction.

Thus, we can use factory like so:

auto p1 = factory<foo>(foo()); // calls foo(foo&&)
auto p2 = factory<foo>(*p1);   // calls foo(foo const&)

Important rvalue reference properties:

  • For overload resolution, lvalues prefer binding to lvalue references and rvalues prefer binding to rvalue references. Hence why temporaries prefer invoking a move constructor / move assignment operator over a copy constructor / assignment operator.
  • rvalue references will implicitly bind to rvalues and to temporaries that are the result of an implicit conversion. i.e. float f = 0f; int&& i = f; is well formed because float is implicitly convertible to int; the reference would be to a temporary that is the result of the conversion.
  • Named rvalue references are lvalues. Unnamed rvalue references are rvalues. This is important to understand why the std::move call is necessary in: foo&& r = foo(); foo f = std::move(r);

How to calculate percentage with a SQL statement

  1. The most efficient (using over()).

    select Grade, count(*) * 100.0 / sum(count(*)) over()
    from MyTable
    group by Grade
    
  2. Universal (any SQL version).

    select Grade, count(*) * 100.0 / (select count(*) from MyTable)
    from MyTable
    group by Grade;
    
  3. With CTE, the least efficient.

    with t(Grade, GradeCount) 
    as 
    ( 
        select Grade, count(*) 
        from MyTable
        group by Grade
    )
    select Grade, GradeCount * 100.0/(select sum(GradeCount) from t)
    from t;
    

Convert a SQL Server datetime to a shorter date format

In addition to CAST and CONVERT, if you are using Sql Server 2008, you can convert to a date type (or use that type to start with), and then optionally convert again to a varchar:

declare @myDate date
set @myDate = getdate()
print cast(@myDate as varchar(10))

output:

2012-01-17

ActiveModel::ForbiddenAttributesError when creating new user

If you are on Rails 4 and you get this error, it could happen if you are using enum on the model if you've defined with symbols like this:

class User
  enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end

The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum to strings instead of symbols

enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']

How to create global variables accessible in all views using Express / Node.JS?

you can also use "global"

Example:

declare like this :

  app.use(function(req,res,next){
      global.site_url = req.headers.host;   // hostname = 'localhost:8080'
      next();
   });

Use like this: in any views or ejs file <% console.log(site_url); %>

in js files console.log(site_url);

How to get value of a div using javascript

As I said in the comments, a <div> element does not have a value attribute. Although (very) bad, it can be accessed as:

console.log(document.getElementById('demo').getAttribute);

I suggest using HTML5 data-* attributes rather. Something like this:

<div id="demo" data-myValue="1">...</div>

in which case you could access it using:

element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');

Display a float with two decimal places in Python

String Formatting:

a = 6.789809823
print('%.2f' %a)

OR

print ("{0:.2f}".format(a)) 

Round Function can be used:

print(round(a, 2))

Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.

b = round(a, 2)
print(b)

How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

If you are using a certificate signed by a Certificate Authority that is not included in the Java cacerts file by default, you need to complete the following configuration for HTTPS connections. To import certificates into cacerts:

  1. Open Windows Explorer and navigate to the cacerts file, which is located in the jre\lib\security subfolder where AX Core Client is installed. The default location is C:\Program Files\ACL Software\AX Core Client\jre\lib\security
  2. Create a backup copy of the file before making any changes.
  3. Depending on the certificates you receive from the Certificate Authority you are using, you may need to import an intermediate certificate and/or root certificate into the cacerts file. Use the following syntax to import certificates: keytool -import -alias -keystore -trustcacerts -file
  4. If you are importing both certificates the alias specified for each certificate should be unique.
  5. Type the password for the keystore at the “Password” prompt and press Enter. The default Java password for the cacerts file is “changeit”. Type ‘y’ at the “Trust this certificate?” prompt and press Enter.

Undefined behavior and sequence points

In C99(ISO/IEC 9899:TC3) which seems absent from this discussion thus far the following steteents are made regarding order of evaluaiton.

[...]the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. (Section 6.5 pp 67)

The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior[sic] is undefined.(Section 6.5.16 pp 91)

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

This works since java 8u40:

Alert alert = new Alert(AlertType.INFORMATION, "Content here", ButtonType.OK);
alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE);
alert.show();

Jump into interface implementation in Eclipse IDE

The best solution would be Ctrl+Alt+I.

How to use "like" and "not like" in SQL MSAccess for the same field?

Try this:

filed like "*AA*" and filed not like "*BB*"

Copy struct to struct in C

Also a good example.....

struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
    struct point ne,se,sw,nw;
}rect_t;
rect_t temp;


int main()
{
//rotate
    RotateRect(&temp);
    return 0;
}

void RotateRect(rect_t *givenRect)
{
    point_t temp_point;
    /*Copy struct data from struct to struct within a struct*/
    temp_point = givenRect->sw;
    givenRect->sw = givenRect->se;
    givenRect->se = givenRect->ne;
    givenRect->ne = givenRect->nw;
    givenRect->nw = temp_point;
}

Initializing a member array in constructor initializer

How about

...
  C() : arr{ {1,2,3} }
{}
...

?

Compiles fine on g++ 4.8

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

Create a GUID in Java

The other Answers are correct, especially this one by Stephen C.

Reaching Outside Java

Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.

If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:

  • Command-line utility
    Bundled with nearly every operating system.
    For example, uuidgen found in Mac OS X, BSD, and Linux.
  • Database server
    Use JDBC to retrieve a UUID generated on the database server.
    For example, the uuid-ossp extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
    • uuid_generate_v1mc() – generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.
    • uuid_generate_v5(namespace uuid, name text) – generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.
  • Web Service
    For example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.

using CASE in the WHERE clause

You don't have to use CASE...WHEN, you could use an OR condition, like this:

WHERE
  pw='correct'
  AND (id>=800 OR success=1) 
  AND YEAR(timestamp)=2011

this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.

It is less common, however you could still use CASE WHEN, like this:

WHERE
  pw='correct'
  AND CASE WHEN id<800 THEN success=1 ELSE TRUE END 
  AND YEAR(timestamp)=2011

this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.

PHP: How to remove specific element from an array?

You can use array filter to remove the items by a specific condition on $v:

$arr = array_filter($arr, function($v){
    return $v != 'some_value';
});

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to fix ReferenceError: primordials is not defined in node

For those who are using yarn.

yarn global add n
n 11.15.0
yarn install # have to install again

Find the number of downloads for a particular app in apple appstore

There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.

How to explicitly obtain post data in Spring MVC?

If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
 //do stuff with valueOne variable here
}

How to install trusted CA certificate on Android device?

I spent a lot of time trying to find an answer to this (I need Android to see StartSSL certificates). Conclusion: Android 2.1 and 2.2 allow you to import certificates, but only for use with WiFi and VPN. There is no user interface for updating the list of trusted root certificates, but there is discussion about adding that feature. It’s unclear whether there is a reliable workaround for manually updating and replacing the cacerts.bks file.

Details and links: http://www.mcbsys.com/techblog/2010/12/android-certificates/. In that post, see the link to Android bug 11231--you might want to add your vote and query to that bug.

What are the best JVM settings for Eclipse?

It is that time of year again: "eclipse.ini take 3" the settings strike back!

Eclipse Helios 3.6 and 3.6.x settings

alt text http://www.eclipse.org/home/promotions/friends-helios/helios.png

After settings for Eclipse Ganymede 3.4.x and Eclipse Galileo 3.5.x, here is an in-depth look at an "optimized" eclipse.ini settings file for Eclipse Helios 3.6.x:

(by "optimized", I mean able to run a full-fledge Eclipse on our crappy workstation at work, some old P4 from 2002 with 2Go RAM and XPSp3. But I have also tested those same settings on Windows7)

Eclipse.ini

alt text

WARNING: for non-windows platform, use the Sun proprietary option -XX:MaxPermSize instead of the Eclipse proprietary option --launcher.XXMaxPermSize.
That is: Unless you are using the latest jdk6u21 build 7. See the Oracle section below.

-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.defaultAction
openFile
-vm
C:/Prog/Java/jdk1.6.0_21/jre/bin/server/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Declipse.p2.unsignedPolicy=allow
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+CMSIncrementalPacing
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/Prog/Java/eclipse_addons

Note:
Adapt the p2.reconciler.dropins.directory to an external directory of your choice.
See this SO answer. The idea is to be able to drop new plugins in a directory independently from any Eclipse installation.

The following sections detail what are in this eclipse.ini file.


The dreaded Oracle JVM 1.6u21 (pre build 7) and Eclipse crashes

Andrew Niefer did alert me to this situation, and wrote a blog post, about a non-standard vm argument (-XX:MaxPermSize) and can cause vms from other vendors to not start at all.
But the eclipse version of that option (--launcher.XXMaxPermSize) is not working with the new JDK (6u21, unless you are using the 6u21 build 7, see below).

The final solution is on the Eclipse Wiki, and for Helios on Windows with 6u21 pre build 7 only:

(eclipse_home)/plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.0.v20100503

That's it. No setting to tweak here (again, only for Helios on Windows with a 6u21 pre build 7).
For non-Windows platform, you need to revert to the Sun proprietary option -XX:MaxPermSize.

The issue is based one a regression: JVM identification fails due to Oracle rebranding in java.exe, and triggered bug 319514 on Eclipse.
Andrew took care of Bug 320005 - [launcher] --launcher.XXMaxPermSize: isSunVM should return true for Oracle, but that will be only for Helios 3.6.1.
Francis Upton, another Eclipse committer, reflects on the all situation.

Update u21b7, July, 27th:
Oracle have regressed the change for the next Java 6 release and won't implement it again until JDK 7.
If you use jdk6u21 build 7, you can revert to the --launcher.XXMaxPermSize (eclipse option) instead of -XX:MaxPermSize (the non-standard option).
The auto-detection happening in the C launcher shim eclipse.exe will still look for the "Sun Microsystems" string, but with 6u21b7, it will now work - again.

For now, I still keep the -XX:MaxPermSize version (because I have no idea when everybody will launch eclipse the right JDK).


Implicit `-startup` and `--launcher.library`

Contrary to the previous settings, the exact path for those modules is not set anymore, which is convenient since it can vary between different Eclipse 3.6.x releases:

  • startup: If not specified, the executable will look in the plugins directory for the org.eclipse.equinox.launcher bundle with the highest version.
  • launcher.library: If not specified, the executable looks in the plugins directory for the appropriate org.eclipse.equinox.launcher.[platform] fragment with the highest version and uses the shared library named eclipse_* inside.

Use JDK6

The JDK6 is now explicitly required to launch Eclipse:

-Dosgi.requiredJavaVersion = 1.6

This SO question reports a positive incidence for development on Mac OS.


+UnlockExperimentalVMOptions

The following options are part of some of the experimental options of the Sun JVM.

-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods

They have been reported in this blog post to potentially speed up Eclipse.
See all the JVM options here and also in the official Java Hotspot options page.
Note: the detailed list of those options reports that UseFastAccessorMethods might be active by default.

See also "Update your JVM":

As a reminder, G1 is the new garbage collector in preparation for the JDK 7, but already used in the version 6 release from u17.


Opening files in Eclipse from the command line

See the blog post from Andrew Niefer reporting this new option:

--launcher.defaultAction
openFile

This tells the launcher that if it is called with a command line that only contains arguments that don't start with "-", then those arguments should be treated as if they followed "--launcher.openFile".

eclipse myFile.txt

This is the kind of command line the launcher will receive on windows when you double click a file that is associated with eclipse, or you select files and choose "Open With" or "Send To" Eclipse.

Relative paths will be resolved first against the current working directory, and second against the eclipse program directory.

See bug 301033 for reference. Originally bug 4922 (October 2001, fixed 9 years later).


p2 and the Unsigned Dialog Prompt

If you are tired of this dialog box during the installation of your many plugins:

alt text

, add in your eclipse.ini:

-Declipse.p2.unsignedPolicy=allow

See this blog post from Chris Aniszczy, and the bug report 235526.

I do want to say that security research supports the fact that less prompts are better.
People ignore things that pop up in the flow of something they want to get done.

For 3.6, we should not pop up warnings in the middle of the flow - no matter how much we simplify, people will just ignore them.
Instead, we should collect all the problems, do not install those bundles with problems, and instead bring the user back to a point in the workflow where they can fixup - add trust, configure security policy more loosely, etc. This is called 'safe staging'.

---------- http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif alt text http://www.eclipse.org/home/categories/images/wiki.gif

Additional options

Those options are not directly in the eclipse.ini above, but can come in handy if needed.


The `user.home` issue on Windows7

When eclipse starts, it will read its keystore file (where passwords are kept), a file located in user.home.
If for some reason that user.home doesn't resolve itself properly to a full-fledge path, Eclipse won't start.
Initially raised in this SO question, if you experience this, you need to redefine the keystore file to an explicit path (no more user.home to resolve at the start)

Add in your eclipse.ini:

-eclipse.keyring 
C:\eclipse\keyring.txt

This has been tracked by bug 300577, it has been solve in this other SO question.


Debug mode

Wait, there's more than one setting file in Eclipse.
if you add to your eclipse.ini the option:

-debug

, you enable the debug mode and Eclipse will look for another setting file: a .options file where you can specify some OSGI options.
And that is great when you are adding new plugins through the dropins folder.
Add in your .options file the following settings, as described in this blog post "Dropins diagnosis":

org.eclipse.equinox.p2.core/debug=true
org.eclipse.equinox.p2.core/reconciler=true

P2 will inform you what bundles were found in dropins/ folder, what request was generated, and what is the plan of installation. Maybe it is not detailed explanation of what actually happened, and what went wrong, but it should give you strong information about where to start:

  • was your bundle in the plan?
  • Was it installation problem (P2 fault)
  • or maybe it is just not optimal to include your feature?

That comes from Bug 264924 - [reconciler] No diagnosis of dropins problems, which finally solves the following issue like:

Unzip eclipse-SDK-3.5M5-win32.zip to ..../eclipse
Unzip mdt-ocl-SDK-1.3.0M5.zip to ..../eclipse/dropins/mdt-ocl-SDK-1.3.0M5

This is a problematic configuration since OCL depends on EMF which is missing.
3.5M5 provides no diagnosis of this problem.

Start eclipse.
No obvious problems. Nothing in Error Log.

  • Help / About / Plugin details shows org.eclipse.ocl.doc, but not org.eclipse.ocl.
  • Help / About / Configuration details has no (diagnostic) mention of org.eclipse.ocl.
  • Help / Installation / Information Installed Software has no mention of org.eclipse.ocl.

Where are the nice error markers?


Manifest Classpath

See this blog post:

  • In Galileo (aka Eclipse 3.5), JDT started resolving manifest classpath in libraries added to project’s build path. This worked whether the library was added to project’s build path directly or via a classpath container, such as the user library facility provided by JDT or one implemented by a third party.
  • In Helios, this behavior was changed to exclude classpath containers from manifest classpath resolution.

That means some of your projects might no longer compile in Helios.
If you want to revert to Galileo behavior, add:

-DresolveReferencedLibrariesForContainers=true

See bug 305037, bug 313965 and bug 313890 for references.


IPV4 stack

This SO question mentions a potential fix when not accessing to plugin update sites:

-Djava.net.preferIPv4Stack=true

Mentioned here just in case it could help in your configuration.


JVM1.7x64 potential optimizations

This article reports:

For the record, the very fastest options I have found so far for my bench test with the 1.7 x64 JVM n Windows are:

-Xincgc 
-XX:-DontCompileHugeMethods 
-XX:MaxInlineSize=1024  
-XX:FreqInlineSize=1024 

But I am still working on it...

Change the spacing of tick marks on the axis of a plot?

And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:

plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))

Wildcard string comparison in Javascript

I used the answer by @Spenhouet and added more "replacements"-possibilities than "*". For example "?". Just add your needs to the dict in replaceHelper.

/**
 * @param {string} str
 * @param {string} rule
 * checks match a string to a rule
 * Rule allows * as zero to unlimited numbers and ? as zero to one character
 * @returns {boolean}
 */
function matchRule(str, rule) {
  const escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  return new RegExp("^" + replaceHelper(rule, {"*": "\\d*", "?": ".?"}, escapeRegex) + "$").test(str);
}

function replaceHelper(input, replace_dict, last_map) {
  if (Object.keys(replace_dict).length === 0) {
    return last_map(input);
  }
  const split_by = Object.keys(replace_dict)[0];
  const replace_with = replace_dict[split_by];
  delete replace_dict[split_by];
  return input.split(split_by).map((next_input) => replaceHelper(next_input, replace_dict, last_map)).join(replace_with);
}

How to terminate a python subprocess launched with shell=True

When shell=True the shell is the child process, and the commands are its children. So any SIGTERM or SIGKILL will kill the shell but not its child processes, and I don't remember a good way to do it. The best way I can think of is to use shell=False, otherwise when you kill the parent shell process, it will leave a defunct shell process.

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

There are a lot of great answers for this issue but I have a noobie answer.

I found that I accidentally added the same Script in two places and it was trying to bind twice. So before you pull your hair out on a simple mistake, make sure you check for this issue.

Why when I transfer a file through SFTP, it takes longer than FTP?

For comparison, I tried transfering a 299GB ntfs disk image from an i5 laptop running Raring Ringtail Ubuntu alpha 2 live cd to an i7 desktop running Ubuntu 12.04.1. Reported speeds:

over wifi + powerline: scp: 5MB/sec (40 Mbit/sec)

over gigabit ethernet + netgear G5608 v3:

scp: 44MB/sec

sftp: 47MB/sec

sftp -C: 13MB/sec

So, over a good gigabit link, sftp is slightly faster than scp, 2010-era fast CPUs seem fast enough to encrypt, but compression isn't a win in all cases.

Over a bad gigabit ethernet link, though, I've had sftp far outperform scp. Something about scp being very chatty, see "scp UNBELIEVABLY slow" on comp.security.ssh from 2008: https://groups.google.com/forum/?fromgroups=#!topic/comp.security.ssh/ldPV3msFFQw http://fixunix.com/ssh/368694-scp-unbelievably-slow.html

SQL Server 2008 - Help writing simple INSERT Trigger

You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

So to insert Employee / Department pairs that do not currently exist you might try something like the following.

CREATE TRIGGER trig_Update_Employee
ON [EmployeeResult]
FOR INSERT
AS
Begin
    Insert into Employee (Name, Department) 
    Select Distinct i.Name, i.Department 
    from Inserted i
    Left Join Employee e
    on i.Name = e.Name and i.Department = e.Department
    where e.Name is null
End

HTML - How to do a Confirmation popup to a Submit button and then send the request?

I believe you want to use confirm()

<script type="text/javascript">
    function clicked() {
       if (confirm('Do you want to submit?')) {
           yourformelement.submit();
       } else {
           return false;
       }
    }

</script>

How to get a key in a JavaScript object by its value?

this worked for me to get key/value of object.

_x000D_
_x000D_
let obj = {_x000D_
        'key1': 'value1',_x000D_
        'key2': 'value2',_x000D_
        'key3': 'value3',_x000D_
        'key4': 'value4'_x000D_
    }_x000D_
    Object.keys(obj).map(function(k){ _x000D_
    console.log("key with value: "+k +" = "+obj[k])    _x000D_
    _x000D_
    })_x000D_
    
_x000D_
_x000D_
_x000D_

How to read a single character from the user?

Try this with pygame:

import pygame
pygame.init()             // eliminate error, pygame.error: video system not initialized
keys = pygame.key.get_pressed()

if keys[pygame.K_SPACE]:
    d = "space key"

print "You pressed the", d, "."

How do I test if a recordSet is empty? isNull?

RecordCount is what you want to use.

If Not temp_rst1.RecordCount > 0 ...

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

Get all variables sent with POST?

Using this u can get all post variable

print_r($_POST)

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Open the file :

WEB-INF -> web.xml

In my case, it looks like as following. :

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Integration Web Services</web-resource-name>
        <description>Integration Web Services accessible by authorized users</description>
        <url-pattern>/services/*</url-pattern>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
        <description>Roles that have access to Integration Web Services</description>
        <role-name>maximouser</role-name>
    </auth-constraint>
    <user-data-constraint>
        <description>Data Transmission Guarantee</description>
        <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
</security-constraint>

Remove or comment these lines.

Error sending json in POST to web API service

another tip...where to add "content-type: application/json"...to the textbox field on the Composer/Parsed tab. There are 3 lines already filled in there, so I added this Content-type as the 4th line. That made the Post work.

The connection to adb is down, and a severe error has occurred

Sounds a bit familiar with my problem: aapt not found under the right path

I needed to clean all open projects to get it working again...

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

Create a CSV File for a user in PHP

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

How do we update URL or query strings using javascript/jQuery without reloading the page?

Use

window.history.replaceState({}, document.title, updatedUri);

To update Url without reloading the page

 var url = window.location.href;
 var urlParts = url.split('?');
 if (urlParts.length > 0) {
     var baseUrl = urlParts[0];
     var queryString = urlParts[1];

     //update queryString in here...I have added a new string at the end in this example
     var updatedQueryString = queryString + 'this_is_the_new_url' 

     var updatedUri = baseUrl + '?' + updatedQueryString;
     window.history.replaceState({}, document.title, updatedUri);
 }

To remove Query string without reloading the page

var url = window.location.href;
if (url.indexOf("?") > 0) {
     var updatedUri = url.substring(0, url.indexOf("?"));
     window.history.replaceState({}, document.title, updatedUri);
}

How unique is UUID?

I concur with the other answers. UUIDs are safe enough for nearly all practical purposes1, and certainly for yours.

But suppose (hypothetically) that they aren't.

Is there a better system or a pattern of some type to alleviate this issue?

Here are a couple of approaches:

  1. Use a bigger UUID. For instance, instead of a 128 random bits, use 256 or 512 or ... Each bit you add to a type-4 style UUID will reduce the probability of a collision by a half, assuming that you have a reliable source of entropy2.

  2. Build a centralized or distributed service that generates UUIDs and records each and every one it has ever issued. Each time it generates a new one, it checks that the UUID has never been issued before. Such a service would be technically straight-forward to implement (I think) if we assumed that the people running the service were absolutely trustworthy, incorruptible, etcetera. Unfortunately, they aren't ... especially when there is the possibility of governments' security organizations interfering. So, this approach is probably impractical, and may be3 impossible in the real world.


1 - If uniqueness of UUIDs determined whether nuclear missiles got launched at your country's capital city, a lot of your fellow citizens would not be convinced by "the probability is extremely low". Hence my "nearly all" qualification.

2 - And here's a philosophical question for you. Is anything ever truly random? How would we know if it wasn't? Is the universe as we know it a simulation? Is there a God who might conceivably "tweak" the laws of physics to alter an outcome?

3 - If anyone knows of any research papers on this problem, please comment.

List of special characters for SQL LIKE clause

You should add that you have to add an extra ' to escape an exising ' in SQL Server:

smith's -> smith''s

Rotating videos with FFmpeg

Unfortunately, the Ubuntu version of ffmpeg does support videofilters.

You need to use avidemux or some other editor to achieve the same effect.

In the programmatic way, mencoder has been recommended.

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

How can I use numpy.correlate to do autocorrelation?

I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:

def autocorrelate(x, period):

    # x is a deep indicator array 
    # period of sample and slices of comparison

    # oldest data (period of input array) may be nan; remove it
    x = x[-np.count_nonzero(~np.isnan(x)):]
    # subtract mean to normalize indicator
    x -= np.mean(x)
    # isolate the recent sample to be autocorrelated
    sample = x[-period:]
    # create slices of indicator data
    correls = []
    for n in range((len(x)-1), period, -1):
        alpha = period + n
        slices = (x[-alpha:])[:period]
        # compare each slice to the recent sample
        correls.append(ta.CORREL(slices, sample, period)[-1])
    # fill in zeros for sample overlap period of recent correlations    
    for n in range(period,0,-1):
        correls.append(0)
    # oldest data (autocorrelation period) will be nan; remove it
    correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])      

    return correls

# CORRELATION OF BEST FIT
# the highest value correlation    
max_value = np.max(correls)
# index of the best correlation
max_index = np.argmax(correls)

Can two applications listen to the same port?

If by applications you mean multiple processes then yes but generally NO. For example Apache server runs multiple processes on same port (generally 80).It's done by designating one of the process to actually bind to the port and then use that process to do handovers to various processes which are accepting connections.

How to find indices of all occurrences of one string in another in JavaScript?

Check this solution which will able to find same character string too, let me know if something missing or not right.

_x000D_
_x000D_
function indexes(source, find) {_x000D_
    if (!source) {_x000D_
      return [];_x000D_
    }_x000D_
    if (!find) {_x000D_
        return source.split('').map(function(_, i) { return i; });_x000D_
    }_x000D_
    source = source.toLowerCase();_x000D_
    find = find.toLowerCase();_x000D_
    var result = [];_x000D_
    var i = 0;_x000D_
    while(i < source.length) {_x000D_
      if (source.substring(i, i + find.length) == find)_x000D_
        result.push(i++);_x000D_
      else_x000D_
        i++_x000D_
    }_x000D_
    return result;_x000D_
  }_x000D_
  console.log(indexes('aaaaaaaa', 'aaaaaa'))_x000D_
  console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))_x000D_
  console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))_x000D_
  console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
_x000D_
_x000D_
_x000D_

How to enable php7 module in apache?

For Windows users looking for solution of same problem. I just repleced

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

in my /conf/extra/http?-xampp.conf

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

In Java, how do I check if a string contains a substring (ignoring case)?

I'd use a combination of the contains method and the toUpper method that are part of the String class. An example is below:

String string1 = "AAABBBCCC"; 
String string2 = "DDDEEEFFF";
String searchForThis = "AABB";

System.out.println("Search1="+string1.toUpperCase().contains(searchForThis.toUpperCase()));

System.out.println("Search2="+string2.toUpperCase().contains(searchForThis.toUpperCase()));

This will return:

Search1=true
Search2=false

How to return a complex JSON response with Node.js?

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

How to move the cursor word by word in the OS X Terminal

Hold down the Option key and click where you'd like the cursor to move

How to call javascript from a href?

Edit This will create a link with Edit after clicking on editing a function name as edit will be called.

How to play .mp4 video in videoview in android?

Use Like this:

Uri uri = Uri.parse(URL); //Declare your url here.

VideoView mVideoView  = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));       
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();

Another Method:

  String LINK = "type_here_the_link";
  VideoView mVideoView  = (VideoView) findViewById(R.id.videoview);
  MediaController mc = new MediaController(this);
  mc.setAnchorView(videoView);
  mc.setMediaPlayer(videoView);
  Uri video = Uri.parse(LINK);
  mVideoView.setMediaController(mc);
  mVideoView.setVideoURI(video);
  mVideoView.start();

If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution.

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

How can I check for IsPostBack in JavaScript?

You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.

bootstrap popover not showing on top of all elements

Problem solved with data-container="body" and z-index
1->
<div class="button btn-align"
data-container="body"  
data-toggle="popover"
data-placement="top"
title="Top"
data-trigger="hover"
data-title-backcolor="#fff"
data-content="A top aligned popover is a really boring thing in the real 
life.">Top</div>
2->
.ggpopover.in {
z-index: 9999 !important;
}

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

Algorithm: efficient way to remove duplicate integers from an array

Simply take a variable x=arr[0] and do xor operation by traversing the rest of the elements . If an element has repeated then the x will become zero.

This way we know that the element has repeated previously . This also will just take o(n) to scan through all of the elements in the original array.

Add new value to an existing array in JavaScript

array = ["value1", "value2", "value3"]

it's not so much jquery as javascript

How to split a long array into smaller arrays, with JavaScript

Just loop over the array, splicing it until it's all consumed.



var a = ['a','b','c','d','e','f','g']
  , chunk

while (a.length > 0) {

  chunk = a.splice(0,3)

  console.log(chunk)

}

output


[ 'a', 'b', 'c' ]
[ 'd', 'e', 'f' ]
[ 'g' ]

Load content with ajax in bootstrap modal

Here is how I solved the issue, might be useful to some:

Ajax modal doesn't seem to be available with boostrap 2.1.1

So I ended up coding it myself:

$('[data-toggle="modal"]').click(function(e) {
  e.preventDefault();
  var url = $(this).attr('href');
  //var modal_id = $(this).attr('data-target');
  $.get(url, function(data) {
      $(data).modal();
  });
});

Example of a link that calls a modal:

<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
    <img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>

I now send the whole modal markup through ajax.

Credits to drewjoh

Get top first record from duplicate records having no unique identity

SELECT TOP 1000 MAX(tel) FROM TableName WHERE Id IN 
(
SELECT Id FROM TableName
GROUP BY Id
HAVING COUNT(*) > 1
) 
GROUP BY Id

C# Creating and using Functions

you have to make you're function static like this

namespace Add_Function
{
  class Program
  {
    public static void(string[] args)
    {
       int a;
       int b;
       int c;

       Console.WriteLine("Enter value of 'a':");
       a = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Enter value of 'b':");
       b = Convert.ToInt32(Console.ReadLine());

       //why can't I not use it this way?
       c = Add(a, b);
       Console.WriteLine("a + b = {0}", c);
    }
    public static int Add(int x, int y)
    {
        int result = x + y;
        return result;
     }
  }
}

you can do Program.Add instead of Add you also can make a new instance of Program by going like this

Program programinstance = new Program();

Passing references to pointers in C++

myfunc("string*& val") this itself doesn't make any sense. "string*& val" implies "string val",* and & cancels each other. Finally one can not pas string variable to a function("string val"). Only basic data types can be passed to a function, for other data types need to pass as pointer or reference. You can have either string& val or string* val to a function.

urllib2 and json

You certainly want to hack the header to have a proper Ajax Request :

headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
           'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()

And to json.loads the POST on the server-side.

Edit : By the way, you have to urllib.urlencode(mydata_dict) before sending them. If you don't, the POST won't be what the server expect

How to get the list of files in a directory in a shell script?

for entry in "$search_dir"/* "$work_dir"/*
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

How to generate a random String in Java

You can also use UUID class from java.util package, which returns random uuid of 32bit characters String.

java.util.UUID.randomUUID().toString()

http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

How do I change the language of moment.js?

After struggling, this worked for me for moment v2.26.0:

import React from "react";
import moment from "moment";
import frLocale from "moment/locale/fr";
import esLocale from "moment/locale/es";

export default function App() {
  moment.locale('fr', [frLocale, esLocale]) // can pass in 'en', 'fr', or 'es'

  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

You can pass in en, fr or es. If you wanted another language, you'd have to import the locale and add it to the array.

If you only need to support one language it is a bit simpler:

import React from "react";
import moment from "moment";
import "moment/locale/fr"; //always use French

export default function App() {  
  let x = moment("2020-01-01 00:00:01");
  return (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

Split string on whitespace in Python

Another method through re module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

Above regex would match one or more non-space characters.

How to Set Variables in a Laravel Blade Template

In laravel document https://laravel.com/docs/5.8/blade#php You can do this way:

@php
     $my_variable = 123;
@endphp

Draggable div without jQuery UI

Here's another updated code:

$(document).ready(function() {
    var $dragging = null;
    $('body').on("mousedown", "div", function(e) {
        $(this).attr('unselectable', 'on').addClass('draggable');
        var el_w = $('.draggable').outerWidth(),
            el_h = $('.draggable').outerHeight();
        $('body').on("mousemove", function(e) {
            if ($dragging) {
                $dragging.offset({
                    top: e.pageY - el_h / 2,
                    left: e.pageX - el_w / 2
                });
            }
        });
        $dragging = $(e.target);
    }).on("mouseup", ".draggable", function(e) {
        $dragging = null;
        $(this).removeAttr('unselectable').removeClass('draggable');
    });
});?

Demo: http://jsfiddle.net/tovic/Jge9z/31/


I've created a simple plugin to this thread.

// Simple JQuery Draggable Plugin
// https://plus.google.com/108949996304093815163/about
// Usage: $(selector).drags();
// Options:
// handle            => your dragging handle.
//                      If not defined, then the whole body of the
//                      selected element will be draggable
// cursor            => define your draggable element cursor type
// draggableClass    => define the draggable class
// activeHandleClass => define the active handle class
//
// Update: 26 February 2013
// 1. Move the `z-index` manipulation from the plugin to CSS declaration
// 2. Fix the laggy effect, because at the first time I made this plugin,
//    I just use the `draggable` class that's added to the element
//    when the element is clicked to select the current draggable element. (Sorry about my bad English!)
// 3. Move the `draggable` and `active-handle` class as a part of the plugin option
// Next update?? NEVER!!! Should create a similar plugin that is not called `simple`!

(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({
            handle: "",
            cursor: "move",
            draggableClass: "draggable",
            activeHandleClass: "active-handle"
        }, opt);

        var $selected = null;
        var $elements = (opt.handle === "") ? this : this.find(opt.handle);

        $elements.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                $selected = $(this);
                $selected.addClass(opt.draggableClass);
            } else {
                $selected = $(this).parent();
                $selected.addClass(opt.draggableClass).find(opt.handle).addClass(opt.activeHandleClass);
            }
            var drg_h = $selected.outerHeight(),
                drg_w = $selected.outerWidth(),
                pos_y = $selected.offset().top + drg_h - e.pageY,
                pos_x = $selected.offset().left + drg_w - e.pageX;
            $(document).on("mousemove", function(e) {
                $selected.offset({
                    top: e.pageY + pos_y - drg_h,
                    left: e.pageX + pos_x - drg_w
                });
            }).on("mouseup", function() {
                $(this).off("mousemove"); // Unbind events from document
                if ($selected !== null) {
                    $selected.removeClass(opt.draggableClass);
                    $selected = null;
                }
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $selected.removeClass(opt.draggableClass);
            } else {
                $selected.removeClass(opt.draggableClass)
                    .find(opt.handle).removeClass(opt.activeHandleClass);
            }
            $selected = null;
        });

        return this;

    };
})(jQuery);

Demo: http://tovic.github.io/dte-project/jquery-draggable/index.html

Way to go from recursion to iteration

Even using stack will not convert a recursive algorithm into iterative. Normal recursion is function based recursion and if we use stack then it becomes stack based recursion. But its still recursion.

For recursive algorithms, space complexity is O(N) and time complexity is O(N). For iterative algorithms, space complexity is O(1) and time complexity is O(N).

But if we use stack things in terms of complexity remains same. I think only tail recursion can be converted into iteration.

Oracle date function for the previous month

Modifying Ben's query little bit,

 select count(distinct switch_id)   
  from [email protected]  
 where dealer_name =  'XXXX'    
   and creation_date between add_months(trunc(sysdate,'mm'),-1) and last_day(add_months(trunc(sysdate,'mm'),-1))

Checking for Undefined In React

In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
    //
}

And, when an undefined , empty or null value is not expected; you can make it more concise:

if (nextProps.blog && nextProps.blog.content) {
    //
}

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.

I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.

If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.

Hope these helps.

Vertical divider doesn't work in Bootstrap 3

I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.

CSS

.divider-vertical {
    padding-top: 14px;
    padding-bottom: 14px;
}

HTML

<ul class="nav navbar-nav">
    <li class="active"><a href="#">Home</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Faq</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">News</a></li>
    <li class="divider-vertical">&#124;</li>
    <li><a href="#">Contact</a></li>
</ul>

MySQL Error #1133 - Can't find any matching row in the user table

This error can occur if trying to grant privileges for a non-existing user.

It is not clear to me what MySQL considers a non-existing user. But I suspect MySQL considers a user to exist if it can be found by a name (column User) and a host (column Host) in the user table.

If trying to grant privileges to a user that can be found with his name (column User) but not by his name and host (columns User and Host), and not provide a password, then the error occurs.

For example, the following statement triggers the error:

grant all privileges on mydb.* to myuser@'xxx.xxx.xxx.xxx';

This is because, with no password being specified, MySQL cannot create a new user, and thus tries to find an existing user. But no user with the name myuser and the host xxx.xxx.xxx.xxx can be found in the user table.

Whereas providing a password, allows the statement to be executed successfully:

grant all privileges on mydb.* to myuser@'xxx.xxx.xxx.xxx' identified by 'mypassword';

Make sure to reuse the same password of that user you consider exists, if that new "MySQL user" is the same "application user".

Complete the operation by flushing the privileges:

flush privileges;

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

On Linux Mint, the official instructions did not work for me. I had to go into /etc/apt/sources.list.d/additional-repositories.list and change serena to xenial.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim directly as below:

UPDATE *tablename*
   SET *columnname* = trim(*columnname*);

Avoid Adding duplicate elements to a List C#

If you want to save distinct values into a collection you could try HashSet Class. It will automatically remove the duplicate values and save your coding time. :)

Force download a pdf link using javascript/ajax/jquery

If htaccess is an option this will make all PDF links download instead of opening in browser

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

how to read System environment variable in Spring applicationContext

In your bean definition, make sure to include "searchSystemEnvironment" and set it to "true". And if you're using it to build a path to a file, specify it as a file:/// url.

So for example, if you have a config file located in

/testapp/config/my.app.config.properties

then set an environment variable like so:

MY_ENV_VAR_PATH=/testapp/config

and your app can load the file using a bean definition like this:

e.g.

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="searchContextAttributes" value="true" />
    <property name="contextOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value>
        </list>
    </property>
</bean>

Android sqlite how to check if a record exists

Try to use cursor.isNull method. Example:

song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));

Examples of good gotos in C or C++

The classic need for GOTO in C is as follows

for ...
  for ...
    if(breakout_condition) 
      goto final;

final:

There is no straightforward way to break out of nested loops without a goto.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

iOS makes phone numbers clickable by defaults (for obvious reasons). Of course, that adds an extra tag which is overriding your styling if your phone number isn’t already a link.

To fix it, try adding this to your stylesheet: a[href^=tel] { color: inherit; text-decoration: none; }

That should keep your phone numbers styled as you expect without adding extra markup.

How to set MimeBodyPart ContentType to "text/html"?

Don't know why (the method is not documented), but by looking at the source code, this line should do it :

mime_body_part.setHeader("Content-Type", "text/html");

Optional Parameters in Web Api Attribute Routing

For an incoming request like /v1/location/1234, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid and not to deviceid.

I think you should change your route template to be like [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")] and then parse the deiveOrAppid to figure out the type of id.

Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ? character in this case. For example: [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]

send mail to multiple receiver with HTML mailto

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

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

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

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

Why Response.Redirect causes System.Threading.ThreadAbortException?

Response.Redirect() throws an exception to abort the current request.

This KB article describes this behavior (also for the Request.End() and Server.Transfer() methods).

For Response.Redirect() there exists an overload:

Response.Redirect(String url, bool endResponse)

If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).

If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.

Build error: "The process cannot access the file because it is being used by another process"

Deleting Obj, retail and debug folder of the .NET project and re-building again worked for me.

Check if application is installed - Android

You can use this in Kotlin extentions.kt

fun Context.isPackageInstalled(packageName: String): Boolean {
    return try {
        packageManager.getPackageInfo(packageName, 0)
        true
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

Usage

context.isPackageInstalled("com.somepackage.name")

is vs typeof

This should answer that question, and then some.

The second line, if (obj.GetType() == typeof(ClassA)) {}, is faster, for those that don't want to read the article.

(Be aware that they don't do the same thing)

Java constructor/method with optional parameters?

Java doesn't support default parameters. You will need to have two constructors to do what you want.

An alternative if there are lots of possible values with defaults is to use the Builder pattern, whereby you use a helper object with setters.

e.g.

   public class Foo {
     private final String param1;
     private final String param2;

     private Foo(Builder builder) {
       this.param1 = builder.param1;
       this.param2 = builder.param2;
     }
     public static class Builder {
       private String param1 = "defaultForParam1";
       private String param2 = "defaultForParam2";

       public Builder param1(String param1) {
         this.param1 = param1;
         return this;
       }
       public Builder param2(String param1) {
         this.param2 = param2;
         return this;
       }
       public Foo build() {
         return new Foo(this);
       }
     }
   }

which allows you to say:

Foo myFoo = new Foo.Builder().param1("myvalue").build();

which will have a default value for param2.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

Delete from two tables in one query

You should either create a FOREIGN KEY with ON DELETE CASCADE:

ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE

, or do it using two queries in a transaction:

START TRANSACTION;;

DELETE
FROM    usermessages
WHERE   messageid = 1

DELETE
FROM    messages
WHERE   messageid = 1;

COMMIT;

Transaction affects only InnoDB tables, though.

error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

Getting input values from text box

This is the sample code for the email and javascript.

params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += "      Query:    ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');

What are the differences between a clustered and a non-clustered index?

Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.

Non-clustered indexes are stored separately, and you can have as many as you want.

The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

How to center HTML5 Videos?

Use margins <video> is an inline element so you'll have to add display block;to your css class.

You can use specific with, but I wouldn’t use px values. Use % to make it responsive, like:

width: 50%;

That’ll make the video half of the viewport width.

See the original documentation here O World Wide Web Consortium W3C

mystyle.css

_x000D_
_x000D_
video {_x000D_
      width: 50% !important;_x000D_
      height: auto !important;_x000D_
      margin: 0 auto;_x000D_
      display: block;_x000D_
    }_x000D_
_x000D_
    h1 {_x000D_
      text-align: center;_x000D_
      color: #C42021;_x000D_
      font-size: 20px;_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
        <html>_x000D_
           <head>_x000D_
              <meta charset="UTF-8">_x000D_
              <title>Test</title>_x000D_
               <link rel="stylesheet" type="text/css" href="mystyle.css">_x000D_
           </head>_x000D_
           <body>_x000D_
              <h1>_x000D_
                 How do you center a video _x000D_
              </h1>_x000D_
              <div class="center">_x000D_
                 <video controls="controls">_x000D_
                    <source src="https://repositorio.ufsc.br/xmlui/bitstream/handle/123456789/100149/Vídeo%20convertido.mp4" type="video/mp4" />_x000D_
                 </video>_x000D_
              </div>_x000D_
           </body>_x000D_
        </html>
_x000D_
_x000D_
_x000D_

See the code ready here for more understanding.

You can view the code online Fiddle

jQuery if div contains this text, replace that part of the text

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

How can I get the current contents of an element in webdriver

In Java its Webelement.getText() . Not sure about python.

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

Make XAMPP / Apache serve file outside of htdocs folder

If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.

For example the following won't work, DocumentRoot "X:/webroot"

But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)

Open CSV file via VBA (performance)

This may help you, also it depends how your CSV file is formated.

  1. Open your excel sheet & go to menu Data > Import External Data > Import Data.
  2. Choose your CSV file.
  3. Original data type: choose Fixed width, then Next.
  4. It will autmaticall delimit your columns. then, you may check the splitted columns in Data preview panel.
  5. Then Finish & see.

Note: you may also go with Delimited as Original data type. In that case, you need to key-in your delimiting character.

HTH!

How to split CSV files as per number of rows specified?

Use the Linux split command:

split -l 20 file.txt new    

Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.

Type man split at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail command, for example) and then add it back on to each of the split files.

How to find out what type of a Mat object is with Mat::type() in OpenCV

I always use this link to see what type is the number I get with type():
LIST OF MAT TYPE IN OPENCV
I hope this can help you.

Pythonic way to check if a list is sorted or not

Actually we are not giving the answer anijhaw is looking for. Here is the one liner:

all(l[i] <= l[i+1] for i in xrange(len(l)-1))

For Python 3:

all(l[i] <= l[i+1] for i in range(len(l)-1))

Rails ActiveRecord date between

Just a note that the currently accepted answer is deprecated in Rails 3. You should do this instead:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

Or, if you want to or have to use pure string conditions, you can do:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)

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.

DataGridView AutoFit and Fill

This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.

When the grid go to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode to AllCells as the others visible columns. For performance issues it´s important to set them to None before data binding it and set back to AllCell in the DataBindingComplete event handler of the grid. Hope it helps!

private void dataGridView1_Resize(object sender, EventArgs e)
    {
        int ColumnsWidth = 0;
        foreach(DataGridViewColumn col in dataGridView1.Columns)
        {
            if (col.Visible) ColumnsWidth += col.Width;
        }

        if (ColumnsWidth <dataGridView1.Width)
        {
            dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        else if (dataGridView1.Columns["first_name"].Width < 10) dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }

Can't access Tomcat using IP address

I was also facing same problem on Amazon windows EC2 instance ( Windows Server 2012 R2 ) Then I figured out , it was local windows firewall preventing it . I opened port 80 ( defined port for website ) using windows Firewall with Advance Security .

It resolved the issue .

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

The C# summarized descendant.

More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx

public sealed class ObservableCollectionEx<T> : ObservableCollection<T>
{
    #region Ctor

    public ObservableCollectionEx()
    {
    }

    public ObservableCollectionEx(List<T> list) : base(list)
    {
    }

    public ObservableCollectionEx(IEnumerable<T> collection) : base(collection)
    {
    }

    #endregion

    /// <summary> 
    /// Adds the elements of the specified collection to the end of the ObservableCollection(Of T). 
    /// </summary> 
    public void AddRange(
        IEnumerable<T> itemsToAdd,
        ECollectionChangeNotificationMode notificationMode = ECollectionChangeNotificationMode.Add)
    {
        if (itemsToAdd == null)
        {
            throw new ArgumentNullException("itemsToAdd");
        }
        CheckReentrancy();

        if (notificationMode == ECollectionChangeNotificationMode.Reset)
        {
            foreach (var i in itemsToAdd)
            {
                Items.Add(i);
            }

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            return;
        }

        int startIndex = Count;
        var changedItems = itemsToAdd is List<T> ? (List<T>) itemsToAdd : new List<T>(itemsToAdd);
        foreach (var i in changedItems)
        {
            Items.Add(i);
        }

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
    }

    public enum ECollectionChangeNotificationMode
    {
        /// <summary>
        /// Notifies that only a portion of data was changed and supplies the changed items (not supported by some elements,
        /// like CollectionView class).
        /// </summary>
        Add,

        /// <summary>
        /// Notifies that the entire collection was changed, does not supply the changed items (may be inneficient with large
        /// collections as requires the full update even if a small portion of items was added).
        /// </summary>
        Reset
    }
}

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Failed to add the host to the list of know hosts

I generated the "ssh" key again and added to my git account. This worked for me.

Please find following commands to generate the "ssh-key":

$ ssh-keygen -t rsa -b 4096 -C "[email protected]"

-> This creates a new ssh key, using the provided email as a label.

Generating public/private rsa key pair.

-> When you're prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]

-> At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases"

Enter passphrase (empty for no passphrase): [Type a passphrase]

Enter same passphrase again: [Type passphrase again]

-> Your key is generated, to copy the key:

$ sudo cat /root/.ssh/id_rsa-pub

Hope this works!

how to remove time from datetime

You may try the following:

SELECT CONVERT(VARCHAR(10),yourdate,101);

or this:

select cast(floor(cast(urdate as float)) as datetime);

Git undo local branch delete

If you deleted a branch via Source Tree, you could easily find the SHA1 of the deleted branch by going to View -> Show Command History.

It should have the next format:

Deleting branch ...
...
Deleted branch %NAME% (was %SHA1%)
...

Then just follow the original answer.

git branch branchName <sha1>

Split string into strings by length?

Here are two generic approaches. Probably worth adding to your own lib of reusables. First one requires the item to be sliceable and second one works with any iterables (but requires their constructor to accept iterable).

def split_bylen(item, maxlen):
    '''
    Requires item to be sliceable (with __getitem__ defined)
    '''
    return [item[ind:ind+maxlen] for ind in range(0, len(item), maxlen)]
    #You could also replace outer [ ] brackets with ( ) to use as generator.

def split_bylen_any(item, maxlen, constructor=None):
    '''
    Works with any iterables.
    Requires item's constructor to accept iterable or alternatively 
    constructor argument could be provided (otherwise use item's class)
    '''
    if constructor is None: constructor = item.__class__
    return [constructor(part) for part in zip(* ([iter(item)] * maxlen))]
    #OR: return map(constructor, zip(* ([iter(item)] * maxlen)))
    #    which would be faster if you need an iterable, not list

So, in topicstarter's case, the usage is:

string = 'Baboons love bananas'
parts = 5
splitlen = -(-len(string) // parts) # is alternative to math.ceil(len/parts)

first_method = split_bylen(string, splitlen)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']

second_method = split_bylen_any(string, splitlen, constructor=''.join)
#Result :['Babo', 'ons ', 'love', ' ban', 'anas']

jQuery - hashchange event

Use Modernizr for detection of feature capabilities. In general jQuery offers to detect browser features: http://api.jquery.com/jQuery.support/. However, hashchange is not on the list.

The wiki of Modernizr offers a list of libraries to add HTML5 capabilities to old browsers. The list for hashchange includes a pointer to the project HTML5 History API, which seems to offer the functionality you would need if you wanted to emulate the behavior in old browsers.

Where can I find the Java SDK in Linux after installing it?

Use find to located it. It should be under /usr somewhere:

find /usr -name java

When running the command, if there are too many "Permission denied" message obfuscating the actual found results then, simply redirect stderr to /dev/null

find /usr -name java 2> /dev/null

Query to display all tablespaces in a database and datafiles

If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:

SQL> connect SYSTEM/fyicenter
Connected.

SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
  2  FROM USER_TABLESPACES;
TABLESPACE_NAME                STATUS    CONTENTS
------------------------------ --------- ---------
SYSTEM                         ONLINE    PERMANENT
UNDO                           ONLINE    UNDO
SYSAUX                         ONLINE    PERMANENT
TEMP                           ONLINE    TEMPORARY
USERS                          ONLINE    PERMANENT

http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

How to export collection to CSV in MongoDB?

For all those who are stuck with an error.

Let me give you guys a solution with a brief explanation of the same:-

command to connect:-

mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin

--host --> host of Mongo server

--port --> port of Mongo server

-u --> username

-p --> password

--db --> db from which you want to export

--collection --> collection you want to export

--type --> type of export in my case CSV

--out --> file name where you want to export

--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)

--authenticationDatabase --> database where all your user information is stored

Space between two rows in a table?

From Mozilla Developer Network:

The border-spacing CSS property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML, but an optional second value can be used to set different horizontal and vertical spacing.

That last part is often overseen. Example:

.your-table {
    border-collapse: separate; /* allow spacing between cell borders */
    border-spacing: 0 5px; /* NOTE: syntax is <horizontal value> <vertical value> */

UPDATE

I now understand that the OP wants specific, seperate rows to have increased spacing. I've added a setup with tbody elements that accomplishes that without ruining the semantics. However, I'm not sure if it is supported on all browsers. I made it in Chrome.

The example below is for showing how you can make it look like the table exists of seperate rows, full blown css sweetness. Also gave the first row more spacing with the tbody setup. Feel free to use!

Support notice: IE8+, Chrome, Firefox, Safari, Opera 4+

_x000D_
_x000D_
.spacing-table {_x000D_
  font-family: 'Helvetica', 'Arial', sans-serif;_x000D_
  font-size: 15px;_x000D_
  border-collapse: separate;_x000D_
  table-layout: fixed;_x000D_
  width: 80%;_x000D_
  border-spacing: 0 5px; /* this is the ultimate fix */_x000D_
}_x000D_
.spacing-table th {_x000D_
  text-align: left;_x000D_
  padding: 5px 15px;_x000D_
}_x000D_
.spacing-table td {_x000D_
  border-width: 3px 0;_x000D_
  width: 50%;_x000D_
  border-color: darkred;_x000D_
  border-style: solid;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  padding: 5px 15px;_x000D_
}_x000D_
.spacing-table td:first-child {_x000D_
  border-left-width: 3px;_x000D_
  border-radius: 5px 0 0 5px;_x000D_
}_x000D_
.spacing-table td:last-child {_x000D_
  border-right-width: 3px;_x000D_
  border-radius: 0 5px 5px 0;_x000D_
}_x000D_
.spacing-table thead {_x000D_
  display: table;_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
}_x000D_
.spacing-table tbody {_x000D_
  display: table;_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
  border-spacing: 0 10px;_x000D_
}
_x000D_
<table class="spacing-table">_x000D_
  <thead>_x000D_
    <tr>_x000D_
        <th>Lead singer</th>_x000D_
        <th>Band</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
        <td>Bono</td>_x000D_
        <td>U2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
        <td>Chris Martin</td>_x000D_
        <td>Coldplay</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Mick Jagger</td>_x000D_
        <td>Rolling Stones</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>John Lennon</td>_x000D_
        <td>The Beatles</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

scroll image with continuous scrolling using marquee tag

Try this:

<marquee behavior="" Height="200px"  direction="up" scroll onmouseover="this.setAttribute('scrollamount', 0, 0);this.stop();" onmouseout="this.setAttribute('scrollamount', 3, 0);this.start();" scrollamount="3" valign="center">

    <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
        <img src="images/a.jpg">
    </marquee>

How do you declare an object array in Java?

It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.

react-router - pass props to handler component

If you'd rather not write wrappers, I guess you could do this:

class Index extends React.Component { 

  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
        Index - {this.props.route.foo}
      </h1>
    );
  }
}

var routes = (
  <Route path="/" foo="bar" component={Index}/>
);

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

How do I select last 5 rows in a table without sorting?

Last 5 rows retrieve in mysql


This query working perfectly

SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC

or

select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc

How to add RSA key to authorized_keys file?

Make sure when executing Michael Krelin's solution you do the following

cat <your_public_key_file> >> ~/.ssh/authorized_keys

Note the double > without the double > the existing contents of authorized_keys will be over-written (nuked!) and that may not be desirable

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

With MySQL, how can I generate a column containing the record index in a table?

You may want to try the following:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r;

The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command.

Test case:

CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);

Test query:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r
WHERE   l.score > 50;

Result:

+----------+----------+-------+------------+
| position | username | score | row_number |
+----------+----------+-------+------------+
|        3 | c        |    75 |          1 |
|        5 | e        |    55 |          2 |
|        6 | f        |    80 |          3 |
+----------+----------+-------+------------+
3 rows in set (0.00 sec)

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Also faced the same problem when using unmanaged c/c++ dll file in c# environment.

1.Checked the compatibility of dll with 32bit or 64bit CPU.

2.Checked the correct paths of DLL .bin folder, system32/sysWOW64 , or given path.

3.Checked if PDB(Programme Database) files are missing.This video gives you ans best undestand about pdb files.

When running 32-bit C/C++ binary code in 64bit system, could arise this because of platform incompatibility. You can change it from Build>Configuration manager.

How to remove jar file from local maven repository which was added with install:install-file?

While there is a maven command you can execute to do this, it's easier to just delete the files manually from the repository.

Like this on windows Documents and Settings\your username\.m2 or $HOME/.m2 on Linux

Sort dataGridView columns in C# ? (Windows Form)

The best way to do this is to sort the list before binding data source.

cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList(); adgCars.DataSource = cars;

Sorry for my bad english.

Command line input in Python

Just Taking Input

the_input = raw_input("Enter input: ")

And that's it.

Moreover, if you want to make a list of inputs, you can do something like:

a = []

for x in xrange(1,10):
    a.append(raw_input("Enter Data: "))

In that case, you'll be asked for data 10 times to store 9 items in a list.

Output:

Enter data: 2
Enter data: 3
Enter data: 4
Enter data: 5
Enter data: 7
Enter data: 3
Enter data: 8
Enter data: 22
Enter data: 5
>>> a
['2', '3', '4', '5', '7', '3', '8', '22', '5']

You can search that list the fundamental way with something like (after making that list):

if '2' in a:
    print "Found"

else: print "Not found."

You can replace '2' with "raw_input()" like this:

if raw_input("Search for: ") in a:
    print "Found"
else: 
    print "Not found"

Taking Raw Data From Input File via Commandline Interface

If you want to take the input from a file you feed through commandline (which is normally what you need when doing code problems for competitions, like Google Code Jam or the ACM/IBM ICPC):

example.py

while(True):
    line = raw_input()
    print "input data: %s" % line

In command line interface:

example.py < input.txt

Hope that helps.

Make first letter of a string upper case (with maximum performance)

string s_Val = "test";
if (s_Val != "")
{
   s_Val  = char.ToUpper(s_Val[0]);
   if (s_Val.Length > 1)
   {
      s_Val += s_Val.Substring(1);
   }
 }

How to display raw html code in PRE or something like it but without escaping it

Cheap and cheerful answer:

<textarea>Some raw content</textarea>

The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim. It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box. You don't need any CSS, JS, escaping, encoding.

You can alter the appearance and behaviour as well. Here's a monospace font, editing disabled, smaller font, no border:

<textarea
    style="width:100%; font-family: Monospace; font-size:10px; border:0;"
    rows="30" disabled
>Some raw content</textarea>

This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

Force the origin to start at 0

Simply add these to your ggplot:

+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

Example

df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for


p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, NA))

enter image description here

Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge' could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

^[A-Za-z](\W|\w)*

(\W|\w) will ensure that every subsequent letter is word(\w) or non word(\W)

instead of (\W|\w)* you can also use .* where . means absolutely anything just like (\w|\W)

jQuery select all except first

$("div.test:not(:first)").hide();

or:

$("div.test:not(:eq(0))").hide();

or:

$("div.test").not(":eq(0)").hide();

or:

$("div.test:gt(0)").hide();

or: (as per @Jordan Lev's comment):

$("div.test").slice(1).hide();

and so on.

See:

Get Application Name/ Label via ADB Shell or Terminal

Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)

  1. Find the APK path of the app whose name you want to find.
  2. Using aapt command, find the app label.

But devices don't ship with the aapt binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries


Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)

An efficient way to transpose a file in Bash

An awk solution that store the whole array in memory

    awk '$0!~/^$/{    i++;
                  split($0,arr,FS);
                  for (j in arr) {
                      out[i,j]=arr[j];
                      if (maxr<j){ maxr=j}     # max number of output rows.
                  }
            }
    END {
        maxc=i                 # max number of output columns.
        for     (j=1; j<=maxr; j++) {
            for (i=1; i<=maxc; i++) {
                printf( "%s:", out[i,j])
            }
            printf( "%s\n","" )
        }
    }' infile

But we may "walk" the file as many times as output rows are needed:

#!/bin/bash
maxf="$(awk '{if (mf<NF); mf=NF}; END{print mf}' infile)"
rowcount=maxf
for (( i=1; i<=rowcount; i++ )); do
    awk -v i="$i" -F " " '{printf("%s\t ", $i)}' infile
    echo
done

Which (for a low count of output rows is faster than the previous code).

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

http://www.kanzaki.com/docs/ical/ has a slightly more readable version of the older spec. It helps as a starting point - many things are still the same.

Also on my site, I have

  1. Some lists of useful resources (see sidebar bottom right) on
    • ical Spec RFC 5545
    • ical Testing Resources
  2. Some notes recorded on my journey working with .ics over the last few years. In particular, you may find this repeating events 'cheatsheet' to be useful.

.ics areas that need careful handling:

  • 'all day' events
  • types of dates (timezone, UTC, or local 'floating') - nb to understand distinction
  • interoperability of recurrence rules

How to convert date into this 'yyyy-MM-dd' format in angular 2

I would suggest you to have a look into Moment.js if you have trouble with Angular. At least it is a quick workaround without spending too much time.

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

How to get current time and date in C++?

C++ shares its date/time functions with C. The tm structure is probably the easiest for a C++ programmer to work with - the following prints today's date:

#include <ctime>
#include <iostream>

int main() {
    std::time_t t = std::time(0);   // get time now
    std::tm* now = std::localtime(&t);
    std::cout << (now->tm_year + 1900) << '-' 
         << (now->tm_mon + 1) << '-'
         <<  now->tm_mday
         << "\n";
}

What does "|=" mean? (pipe equal operator)

| is the bitwise-or operator, and it is being applied like +=.

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

Getting an "ambiguous redirect" error

put quotes around your variable. If it happens to have spaces, it will give you "ambiguous redirect" as well. also check your spelling

echo $AAAA"     "$DDDD"         "$MOL_TAG  >>  "${OUPUT_RESULTS}"

eg of ambiguous redirect

$ var="file with spaces"
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA"     "$DDDD"         "$MOL_TAG >> "${var}"
$ cat file\ with\ spaces
aaaa     dddd         mol_tag

git-upload-pack: command not found, when cloning remote Git repo

Make sure git-upload-pack is on the path from a non-login shell. (On my machine it's in /usr/bin).

To see what your path looks like on the remote machine from a non-login shell, try this:

ssh you@remotemachine echo \$PATH

(That works in Bash, Zsh, and tcsh, and probably other shells too.)

If the path it gives back doesn't include the directory that has git-upload-pack, you need to fix it by setting it in .bashrc (for Bash), .zshenv (for Zsh), .cshrc (for tcsh) or equivalent for your shell.

You will need to make this change on the remote machine.

If you're not sure which path you need to add to your remote PATH, you can find it with this command (you need to run this on the remote machine):

which git-upload-pack

On my machine that prints /usr/bin/git-upload-pack. So in this case, /usr/bin is the path you need to make sure is in your remote non-login shell PATH.

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

I had similar problem. I r?n npm cache clear, closed android SDK manager(which was open before) and re-ran npm install -g cordova and that was enough to solve the problem.