Programs & Examples On #Focusvisualstyle

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

alternative to "!is.null()" in R

I have also seen:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}

I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.

How to initialize an array of objects in Java

If you can hard-code the number of players

Player[] thePlayers = {
    new Player(0),
    new Player(1),
    new Player(2),
    new Player(3)
};

HTML input - name vs. id

The name attribute on an input is used by its parent HTML <form>s to include that element as a member of the HTTP form in a POST request or the query string in a GET request.

The id should be unique as it should be used by JavaScript to select the element in the DOM for manipulation and used in CSS selectors.

How to install PHP mbstring on CentOS 6.2

*Make sure you update your linux box first

yum update

In case someone still has this problem, this is a valid solution:

centos-release : rpm -q centos-release

Centos 6.*

wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
rpm -ivh epel-release-6-8.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6*.rpm

Centos 5.*

wget http://ftp.jaist.ac.jp/pub/Linux/Fedora/epel/5/x86_64/epel-release-5-4.noarch.rpm
rpm -ivh epel-release-5-4.noarch.rpm
wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
rpm -Uvh remi-release-5*.rpm

Then just do this to update:

yum --enablerepo=remi upgrade php-mbstring

Or this to install:

yum --enablerepo=remi install php-mbstring

How to list only files and not directories of a directory Bash?

Listing content of some directory, without subdirectories

I like using ls options, for sample:

  • -l use a long listing format
  • -t sort by modification time, newest first
  • -r reverse order while sorting
  • -F, --classify append indicator (one of */=>@|) to entries
  • -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc...

Sometime --color and all others. (See ls --help)

Listing everything but folders

This will show files, symlinks, devices, pipe, sockets etc.

so

find /some/path -maxdepth 1 ! -type d

could be sorted by date easily:

find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +

Listing files only:

or

find /some/path -maxdepth 1 -type f

sorted by size:

find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +

Prevent listing of hidden entries:

To not show hidden entries, where name begin by a dot, you could add ! -name '.*':

find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +

Then

You could replace /some/path by . to list for current directory or .. for parent directory.

Using an Alias in a WHERE clause

Just as an alternative approach to you can do:

WITH inner_table AS
(SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier)

    SELECT * FROM inner_table 
    WHERE MONTH_NO > UPD_DATE

Also you can create a permanent view for your queue and select from view.

CREATE OR REPLACE VIEW_1 AS (SELECT ...);
SELECT * FROM VIEW_1;

java.io.IOException: Invalid Keystore format

Maybe maven encoding you KeyStore, you can set filtering=false to fix this problem.

<build>
    ...
    <resources>
        <resource>
            ...
            <!-- set filtering=false to fix -->
            <filtering>false</filtering>
            ...
        </resource>
    </resources>
</build>

width:auto for <input> fields

It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

cell format round and display 2 decimal places

Input: 0 0.1 1000

=FIXED(E5,2)

Output: 0.00 0.10 1,000.00

=TEXT(E5,"0.00")

Output: 0.00 0.10 1000.00

Note: As you can see FIXED add a coma after a thousand, where TEXT does not.

Sending GET request with Authentication headers using restTemplate

A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
            HttpHeaders headers = request.getHeaders();
            if (!headers.containsKey("Authorization")) {
                String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                request.getHeaders().add("Authorization", token);
            }
            return clientHttpRequestExecution.execute(request, body);
        });
        return restTemplate;
    }
}

Load local images in React.js

Best approach is to import image in js file and use it. Adding images in public folder have some downside:

  • Files inside public folder not get minified or post-processed,

  • You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,

  • Can't find files at runtime (compilation), result in 404 error at client side.

Skip to next iteration in loop vba

The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.

What you want inside your for loop follows the pattern

If (your condition) Then
    'Do something
End If

In this case, your condition is Not(Return = 0 And Level = 0), so you would use

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If (Not(Return = 0 And Level = 0)) Then
        'Do something
    End If
Next i

PS: the condition is equivalent to (Return <> 0 Or Level <> 0)

Typescript sleep

Or rather than to declare a function, simply:

setTimeout(() => {
    console.log('hello');
}, 1000);

Highcharts - redraw() vs. new Highcharts.chart

you have to call set and add functions on chart object before calling redraw.

chart.xAxis[0].setCategories([2,4,5,6,7], false);

chart.addSeries({
    name: "acx",
    data: [4,5,6,7,8]
}, false);

chart.redraw();

In Perl, how to remove ^M from a file?

You found out you can also do this:

$line=~ tr/\015//d;

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
{
    // ...

    Card(); // <== Declaration of default constructor!

    // ...
};

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {
//nothing
}

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {
//nothing
}

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.


The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.


Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I encountered the same exact error message. I am not quite sure if my solution will solve also your issue.

In Project Structure (app) I changed the Compile SDK Version from API 22 to API 21 and changed Build Tools Version from 22.0.0 to 21.1.2.

When I downloaded the latest API 22 Adroid 5.1, every project I create is using this API and causes me the problem. Maybe, Android Team is looking for a fix for this one.

BLOB to String, SQL Server

The accepted answer works for me only for the first 30 characters. This works for me:

select convert(varchar(max), convert(varbinary(max),myBlobColumn)) FROM table_name

Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.

If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.

You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.

See Unable to send emails to external domain using SMTP for an example of how to send the credentials.

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

The following works for me with nodejs:

xServer.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Accept');

  next();
});

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

Actually, you can achieve this pretty easy. Simply specify the line height as a number:

<p style="line-height:1.5">
    <span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
    <span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>

The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.

For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.

Replace Line Breaks in a String C#

Use replace with Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

How to obtain image size using standard Python class (without using external library)?

Kurts answer needed to be slightly modified to work for me.

First, on ubuntu: sudo apt-get install python-imaging

Then:

from PIL import Image
im=Image.open(filepath)
im.size # (width,height) tuple

Check out the handbook for more info.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

Regex Email validation

This regex works perfectly:

bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}

Extracting Nupkg files using command line

You can also use the NuGet command line, by specifying a local host as part of an install. For example if your package is stored in the current directory

nuget install MyPackage -Source %cd% -OutputDirectory packages

will unpack it into the target directory.

How to retrieve form values from HTTPPOST, dictionary or?

The answers are very good but there is another way in the latest release of MVC and .NET that I really like to use, instead of the "old school" FormCollection and Request keys.


Consider a HTML snippet contained within a form tag that either does an AJAX or FORM POST.

<input type="hidden"   name="TrackingID" 
<input type="text"     name="FirstName"  id="firstnametext" />
<input type="checkbox" name="IsLegal"  value="Do you accept terms and conditions?" />

Your controller will actually parse the form data and try to deliver it to you as parameters of the defined type. I included checkbox because it is a tricky one. It returns text "on" if checked and null if not checked. The requirement though is that these defined variables MUST exists (unless nullable(remember though that string is nullable)) otherwise the AJAX or POST back will fail.

[HttpPost]
public ActionResult PostBack(int TrackingID, string FirstName, string IsLegal){
    MyData.SaveRequest(TrackingID,FirstName, IsLegal == null ? false : true);
}

You can also post back a model without using any razor helpers. I have come across that this is needed some times.

public Class HomeModel
{
  public int HouseNumber { get; set; }
  public string StreetAddress { get; set; }
}

The HTML markup will simply be ...

<input type="text" name="variableName.HouseNumber" id="whateverid" >

and your controller(Razor Engine) will intercept the Form Variable "variableName" (name is as you like but keep it consistent) and try to build it up and cast it to MyModel.

[HttpPost]
public ActionResult PostBack(HomeModel variableName){
    postBack.HouseNumber; //The value user entered
    postBack.StreetAddress; //the default value of NULL.
}

When a controller is expecting a Model (in this case HomeModel) you do not have to define ALL the fields as the parser will just leave them at default, usually NULL. The nice thing is you can mix and match various models on the Mark-up and the post back parse will populate as much as possible. You do not need to define a model on the page or use any helpers.

TIP: The name of the parameter in the controller is the name defined in the HTML mark-up "name=" not the name of the Model but the name of the expected variable in the !


Using List<> is bit more complex in its mark-up.

<input type="text" name="variableNameHere[0].HouseNumber" id="id"           value="0">
<input type="text" name="variableNameHere[1].HouseNumber" id="whateverid-x" value="1">
<input type="text" name="variableNameHere[2].HouseNumber"                   value="2">
<input type="text" name="variableNameHere[3].HouseNumber" id="whateverid22" value="3">

Index on List<> MUST always be zero based and sequential. 0,1,2,3.

[HttpPost]
public ActionResult PostBack(List<HomeModel> variableNameHere){
     int counter = MyHomes.Count()
     foreach(var home in MyHomes)
     { ... }
}

Using IEnumerable<> for non zero based and non sequential indices post back. We need to add an extra hidden input to help the binder.

<input type="hidden" name="variableNameHere.Index" value="278">
<input type="text" name="variableNameHere[278].HouseNumber" id="id"      value="3">

<input type="hidden" name="variableNameHere.Index" value="99976">
<input type="text" name="variableNameHere[99976].HouseNumber" id="id3"   value="4">

<input type="hidden" name="variableNameHere.Index" value="777">
<input type="text" name="variableNameHere[777].HouseNumber" id="id23"    value="5">

And the code just needs to use IEnumerable and call ToList()

[HttpPost]
public ActionResult PostBack(IEnumerable<MyModel> variableNameHere){
     int counter = variableNameHere.ToList().Count()
     foreach(var home in variableNameHere)
     { ... }
}

It is recommended to use a single Model or a ViewModel (Model contianing other models to create a complex 'View' Model) per page. Mixing and matching as proposed could be considered bad practice, but as long as it works and is readable its not BAD. It does however, demonstrate the power and flexiblity of the Razor engine.

So if you need to drop in something arbitrary or override another value from a Razor helper, or just do not feel like making your own helpers, for a single form that uses some unusual combination of data, you can quickly use these methods to accept extra data.

Is there a Google Chrome-only CSS hack?

I have found this works ONLY in Chrome (where it's red) and not Safari and all other browsers (where it's green)...

.style {
color: green;
(-bracket-:hack;
    color: red;
);
}

From http://mynthon.net/howto/webdev/css-hacks-for-google-chrome.htm

DateTime.MinValue and SqlDateTime overflow

If you use DATETIME2 you may find you have to pass the parameter in specifically as DATETIME2, otherwise it may helpfully convert it to DATETIME and have the same issue.

command.Parameters.Add("@FirstRegistration",SqlDbType.DateTime2).Value = installation.FirstRegistration;

Android/Eclipse: how can I add an image in the res/drawable folder?

You just need to copy/cut and paste the images into drawable folder using windows/mac file explorer

To refresh the workspace follow the steps mentioned in this question Eclipse: How do i refresh an entire workspace? F5 doesn't do it

If that does not work you might wanna restart eclispe

UITableView load more when scrolling to bottom like Facebook application

Better to use willDisplayCell method to check if which cell will be loaded. Once we get the current indexPath.row is last we can load more cells. This will load more cells on scrolling down.

 - (void)tableView:(UITableView *)tableView 
       willDisplayCell:(UITableViewCell *)cell    
       forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // check if indexPath.row is last row
    // Perform operation to load new Cell's.
}

Move cursor to end of file in vim

This is quicker. Just use this

:$

Convert array of strings to List<string>

Just use this constructor of List<T>. It accepts any IEnumerable<T> as an argument.

string[] arr = ...
List<string> list = new List<string>(arr);

Convert dictionary values into array

If you would like to use linq, so you can try following:

Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();

I don't know which one is faster or better. Both work for me.

How to delete a file from SD card?

Android Context has the following method:

public abstract boolean deleteFile (String name)

I believe this will do what you want with the right App premissions as listed above.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

This is what i have noticed for the above issue :- If the checkout folder (folder where your pom project resides) is same as the eclipse workspace folder then i am getting this issue

SOLUTION

when i used a separate workspace folder for importing the project, eclipse did worked smoothly :)

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

centos: Another MySQL daemon already running with the same unix socket

in order to clean automatically .sock file, place these lines in file /etc/init.d/mysqld immediately after "start)" block of code

test -e /var/lib/mysql/mysql.sock
SOCKEXIST=$?

ps cax | grep mysqld_safe
NOPIDMYSQL=$?

echo NOPIDMYSQL $NOPIDMYSQL
echo SOCKEXIST $SOCKEXIST

if [ $NOPIDMYSQL -eq 1 ] && [ $SOCKEXIST -eq 0 ] ; then
    echo "NOT CLEAN"
    rm -f /var/lib/mysql/mysql.sock
    echo "FILE SOCK REMOVED"
else
    echo "CLEAN"
fi

it worked for me. I had to do this because I have not an UPS and often we have power supply failures.

regards.

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

It seems that your Java code is using IPv6 instead of IPv4. Please try to use 127.0.0.1 instead of localhost. Ex.: Your connection string should be

jdbc:mysql://127.0.0.1:3306/expeditor?zeroDateTimeBehavior=convertToNull&user=root&password=onelife

P.S.: Please update the URL connection string.

how to make window.open pop up Modal?

I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.

In parent window use:

<head>    
<style>
.disableWin{
     pointer-events: none;
}
</style>
<script type="text/javascript">
    function openPopUp(url) {
      disableParentWin(); 
      var win = window.open(url);
      win.focus();
      checkPopUpClosed(win);
    }
    /*Function to detect pop up is closed and take action to enable parent window*/
   function checkPopUpClosed(win) {
         var timer = setInterval(function() {
              if(win.closed) {
                  clearInterval(timer);                  
                  enableParentWin();
              }
          }, 1000);
     }
     /*Function to enable parent window*/ 
     function enableParentWin() {
          window.document.getElementById('mainDiv').class="";
     }
     /*Function to enable parent window*/ 
     function disableParentWin() {
          window.document.getElementById('mainDiv').class="disableWin";
     }

</script>
</head>

<body>
<div id="mainDiv class="">
</div>
</body>    

img tag displays wrong orientation

This problem was driving me crazy too. I was using PHP on my server side so I was not able to use @The Lazy Log(ruby) & @deweydb(python) solutions. However it pointed me to the right direction. I fixed it on the backed using Imagick's getImageOrientation().

<?php 
// Note: $image is an Imagick object, not a filename! See example use below. 
function autoRotateImage($image) { 
    $orientation = $image->getImageOrientation(); 

    switch($orientation) { 
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees 
        break; 

        case imagick::ORIENTATION_RIGHTTOP: 
            $image->rotateimage("#000", 90); // rotate 90 degrees CW 
        break; 

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW 
        break; 
    } 

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! 
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); 
} 
?> 

Here is the link if you want to read more. http://php.net/manual/en/imagick.getimageorientation.php

escaping question mark in regex javascript

You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:

var gent = /I like your Apartment. Could we schedule a viewing\?/g;

PHP Remove elements from associative array

You can use this

unset($dataArray['key']);

regular expression to match exactly 5 digits

My test string for the following:

testing='12345,abc,123,54321,ab15234,123456,52341';

If I understand your question, you'd want ["12345", "54321", "15234", "52341"].

If JS engines supported regexp lookbehinds, you could do:

testing.match(/(?<!\d)\d{5}(?!\d)/g)

Since it doesn't currently, you could:

testing.match(/(?:^|\D)(\d{5})(?!\d)/g)

and remove the leading non-digit from appropriate results, or:

pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
    result.push(match[1]);
}

Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while loop, otherwise you'll get an infinite loop.

Using group by and having clause

First of all, you should use the JOIN syntax rather than FROM table1, table2, and you should always limit the grouping to as little fields as you need.

Altought I haven't tested, your first query seems fine to me, but could be re-written as:

SELECT s.sid, s.name
FROM 
    Supplier s
    INNER JOIN (
       SELECT su.sid
       FROM Supplies su
       GROUP BY su.sid
       HAVING COUNT(DISTINCT su.jid) > 1
    ) g
        ON g.sid = s.sid

Or simplified as:

SELECT sid, name
FROM Supplier s
WHERE (
    SELECT COUNT(DISTINCT su.jid)
    FROM Supplies su
    WHERE su.sid = s.sid
) > 1

However, your second query seems wrong to me, because you should also GROUP BY pid.

 SELECT s.sid, s.name
    FROM 
        Supplier s
        INNER JOIN (
            SELECT su.sid
            FROM Supplies su
            GROUP BY su.sid, su.pid
            HAVING COUNT(DISTINCT su.jid) > 1
        ) g
            ON g.sid = s.sid

As you may have noticed in the query above, I used the INNER JOIN syntax to perform the filtering, however it can be also written as:

SELECT s.sid, s.name
FROM Supplier s
WHERE (
     SELECT COUNT(DISTINCT su.jid)
     FROM Supplies su
     WHERE su.sid = s.sid
     GROUP BY su.sid, su.pid
) > 1

Ubuntu: OpenJDK 8 - Unable to locate package

UPDATE: installation without root privileges below


I advise you to not install packages manually on ubuntu system if there is already a (semi-official) repository able to solve your problem. Further, use Oracle JDK for development, just to avoid (very sporadic) compatibility issues (i've tried many years ago, it's surely better now).

Add the webupd8 repo to your system:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Install your preferred version of jdk (versions from java-6 to java-9 available):

sudo apt-get install oracle-java8-installer

You can also install multiple version of jdk, mixing openjdk and oracle versions. Then you can use the command update-java-alternatives to switch between installed version:

# list available jdk
update-java-alternatives --list

# use jdk7
sudo update-java-alternatives --set java-7-oracle

# use jdk8
sudo update-java-alternatives --set java-8-oracle

Requirements

If you get add-apt-repository: command not found be sure to have software-properties-common installed:

sudo apt-get install software-properties-common

If you're using an older version Ubuntu:

sudo apt-get install python-software-properties

JDK installation without root privileges

If you haven't administrator rights on your target machine your simplest bet is to use sdkman to install the zulu certified openjdk:

curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install java

NOTE: sdkman allow to install also the official Oracle JDK, although it's not a the default option. View available versions with:

sdk ls java

Install the chosen version with:

sdk install java <version>

For example:

sdk install java 9.0.1-oracle

Glossary of commands

  • sudo <command> [command_arguments]: execute a command with the superuser privilege.

  • add-apt-repository <PPA_id>: Ubuntu (just like every Debian derivatives and generally speaking every Linux distribution) has a main repository of packages that handle things like package dependencies and updating. In Ubuntu is possible to extend the main repository using a PPA (Personal Package Archive) that usually contains packages not available in the system (just like oracle jdk) or updated versions of available ones (example: LibreOffice 5 in LTS is available only through this PPA).

  • apt-get [install|update|upgrade|purge|...]: it's "the" command-line package handler used to manipulate the state of every repository on the system (installing / updating / upgrading can be viewed as an alteration of the repository current state).

In our case: with the command sudo add-apt-repository ppa:webupd8team/java we inform the system that the next repository update must retrieve packages information also from webupd8 repo.

With sudo apt-get update we actually update the system repository (all this operations requires superuser privileges, so we prepend sudo to the commands).

sudo apt-get install oracle-java8-installer

  • update-java-alternatives (a specific java version of update-alternatives): in Ubuntu several packages provides the same functionality (browse the internet, compile mails, edit a text file or provides java/javac executables...). To allows the system to choose the user favourites tool given a specific task a mechanism using symlinks under /etc/alternatives/ is used. Try to update the jdk as indicated above (switch between java 7 and java 8) and view how change the output of this command:

    ls -l /etc/alternatives/java*

In our case: sudo update-java-alternatives --set java-8-oracle update symlinks under /etc/alternatives to point to java-8-oracle executables.

Extras:

  • man <command>: start using man to read a really well written and detailed help on (almost) every shell command and its options (every command i mention in this little answer has a man page, try man update-java-alternatives).

  • apt-cache search <search_key>: query the APT cache to search for a package related with the search_key provided (can be the package name or some word in package description).

  • apt-cache show <package>: provides APT information for a specific package (package version, installed or not, description).

Redirecting from HTTP to HTTPS with PHP

Try something like this (should work for Apache and IIS):

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Python NoneType object is not callable (beginner)

I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it

example: 
Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.

Copying files using rsync from remote server to local machine

From your local machine:

rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage

From your local machine with a non standard ssh port:

rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path

Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:

rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage

See man rsync for an explanation of my usual switches.

Spring MVC: how to create a default controller for index page?

Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml

<mvc:view-controller path="/" view-name="index"/>

After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.

change index with your jsp name.

How to insert newline in string literal?

If you really want the New Line string as a constant, then you can do this:

public readonly string myVar = Environment.NewLine;

The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.

How to identify numpy types in python?

The solution I've come up with is:

isinstance(y, (np.ndarray, np.generic) )

However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray or np.generic, and this probably isn't version robust.

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

Replace only text inside a div using jquery

Just in case if you can't change HTML. Very primitive but short & works. (It will empty the parent div hence the child divs will be removed)

_x000D_
_x000D_
$('#one').text('Hi I am replace');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="one">_x000D_
  <div class="first"></div>_x000D_
  "Hi I am text"_x000D_
  <div class="second"></div>_x000D_
  <div class="third"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I get a value from a map?

The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook

ORDER BY the IN value list

I think this way is better :

SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
    ORDER BY  id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC

Android Gradle Could not reserve enough space for object heap

Faced this issue on Android studio 4.1, windows 10.

The solution that worked for me:

1 - Go to gradle.properties file which is in the root directory of the project.

2 - Comment this line or similar one (org.gradle.jvmargs=-Xmx1536m) to let android studio decide on the best compatible option.

3 - Now close any open project from File -> close project.

4 - On the Welcome window, Go to Configure > Settings.

5 - Go to Build, Execution, Deployment > Compiler

6 - Change Build process heap size (Mbytes) to 1024 and VM Options to -Xmx512m.

Now close the android studio and restart it. The issue will be gone.

Use a normal link to submit a form

Just styling an input type="submit" like this worked for me:

_x000D_
_x000D_
.link-button { _x000D_
     background: none;_x000D_
     border: none;_x000D_
     color: #0066ff;_x000D_
     text-decoration: underline;_x000D_
     cursor: pointer; _x000D_
}
_x000D_
<input type="submit" class="link-button" />
_x000D_
_x000D_
_x000D_

Tested in Chrome, IE 7-9, Firefox

github markdown colspan

Adding break resolves your issue. You can store more than a record in a cell as markdown doesn't support much features.

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

You should use fm element to delete blank spaces.

SELECT TO_CHAR(sysdate, 'fmDAY DD "de" MONTH "de" YYYY') CURRENT_DATE
FROM   dual;

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Convert string to Boolean in javascript

I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).

var myBool = myString == "true";

How to list active / open connections in Oracle?

Select count(1) From V$session
where status='ACTIVE'
/

How to check if bootstrap modal is open, so I can use jquery validate?

On bootstrap-modal.js v2.2.0:

( $('element').data('modal') || {}).isShown

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

How to change text and background color?

Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.

The second way is calling the system colors.

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
    //Changing Font Colors of the System

    system("Color 7C");
    cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
    cout << "\t\t\t  ***                MENU           ***\t\t\t  " <<endl;

    return 0;

}

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

How to make custom error pages work in ASP.NET MVC 4

Here is my solution. Use [ExportModelStateToTempData] / [ImportModelStateFromTempData] is uncomfortable in my opinion.

~/Views/Home/Error.cshtml:

@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Error</h2>
<hr/>

<div style="min-height: 400px;">

    @Html.ValidationMessage("Error")

    <br />
    <br />

    <button onclick="Error_goBack()" class="k-button">Go Back</button>
    <script>
        function Error_goBack() {
            window.history.back()
        }
    </script>

</div>

~/Controllers/HomeController.sc:

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Error()
    {
        return this.View();
    }

    ...
}

~/Controllers/BaseController.sc:

public class BaseController : Controller
{
    public BaseController() { }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (filterContext.Controller.TempData.ContainsKey("Error"))
            {
                var modelState = filterContext.Controller.TempData["Error"] as ModelState;
                filterContext.Controller.ViewData.ModelState.Merge(new ModelStateDictionary() { new KeyValuePair<string, ModelState>("Error", modelState) });
                filterContext.Controller.TempData.Remove("Error");
            }
        }
        if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
        {
            if (filterContext.Controller.ViewData.ModelState.ContainsKey("Error"))
            {
                filterContext.Controller.TempData["Error"] = filterContext.Controller.ViewData.ModelState["Error"];
            }
        }

        base.OnActionExecuted(filterContext);
    }
}

~/Controllers/MyController.sc:

public class MyController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Details(int id)
    {
        if (id != 5)
        {
            ModelState.AddModelError("Error", "Specified row does not exist.");
            return RedirectToAction("Error", "Home");
        }
        else
        {
            return View("Specified row exists.");
        }
    }
}

I wish you successful projects ;-)

How to get difference between two dates in Year/Month/Week/Day?

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{

        int gyear = dateTimePicker1.Value.Year; 
        int gmonth = dateTimePicker1.Value.Month; 
        int gday = dateTimePicker1.Value.Day; 
        int syear = DateTime.Now.Year; 
        int smonth = DateTime.Now.Month; 
        int sday = DateTime.Now.Day;

        int difday = DateTime.DaysInMonth(syear, gmonth);

        agedisplay = (syear - gyear); 

        lmonth = (smonth - gmonth);
        lday = (sday - gday);


        if (smonth < gmonth)
        {
            agedisplay = agedisplay - 1;
        }
        if (smonth == gmonth)
        {
            if (sday < (gday))
            {
                agedisplay = agedisplay - 1;
            }
        }

        if (smonth < gmonth)
        {
            lmonth = (-(-smonth)+(-gmonth)+12);
        }
        if (lday < 0)
        {
            lday = difday - (-lday);
            lmonth = lmonth - 1;
        }

        if (smonth == gmonth && sday < gday&&gyear!=syear)
        {
            lmonth = 11;
        }

            ageDisplay.Text = Convert.ToString(agedisplay) + " Years,  " + lmonth + " Months,  " + lday + " Days.";

    }

It says that TypeError: document.getElementById(...) is null

I have same problem. It just the javascript's script loads too fast--before the HTML's element loaded. So the browser returning null, since the browser can't find where is the element you like to manipulate.

PHP function use variable from outside

Add second parameter

You need to pass additional parameter to your function:

function parts($site_url, $part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
}

In case of closures

If you'd rather use closures then you can import variable to the current scope (the use keyword):

$parts = function($part) use ($site_url) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
};

global - a bad practice

This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

For the completeness sake here is the solution using global:

function parts($part) { 
    global $site_url;
    $structure = 'http://' . $site_url . 'content/'; 
    echo($structure . $part . '.php'); 
}

It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

Suggested reading:

How can I tail a log file in Python?

So, this is coming quite late, but I ran into the same problem again, and there's a much better solution now. Just use pygtail:

Pygtail reads log file lines that have not been read. It will even handle log files that have been rotated. Based on logcheck's logtail2 (http://logcheck.org)

Completely Remove MySQL Ubuntu 14.04 LTS

Remove /etc/my.cnf file and retry the installation, it worked for me for exactly same problem. :-)

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Check whether you are actually under a github repo.

So, listing of .git/ should give you results..otherwise you may be some level outside your repo.

Now, cd to your repo and you are good to go.

Javascript, viewing [object HTMLInputElement]

If the element is an <input type="text">, you should query the value attribute:

alert(element.value);

See an example in this jsFiddle.

Also, and seeing you're starting to learn HTML, you might consider using console.log() instead of alert() for debugging purposes. It doesn't interrupt the execution flow of the script, and you can have a general view of all logs in almost every browser with developer tools (except that one, obviously).

And of course, you could consider using a web development tool like Firebug, for instance, which is a powerful addon for Firefox that provides a lot of functionalities (debugging javascript code, DOM inspector, real-time DOM/CSS changes, request monitoring ...)

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

In case anyone gets the same error I did: “Requirements installation failed with status: 1.” here's what to do:

Install Homebrew (for some reason might not work automatically) with this command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then proceed to install rvm again using

curl -sSL https://get.rvm.io | bash -s stable --ruby

Quit and reopen Terminal and then:

rvm install 2.2
rvm use 2.2 --default

Java path..Error of jvm.cfg

Error:could not open jvm.cfg

Copying and pasting i386\jvm.cfg from a different PC will resolve the issue.

Azure SQL Database "DTU percentage" metric

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

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

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

From down toward the bottom of this announcement:

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

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

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Here are the steps to solve this issue:

  1. Just go to your MongoDB bin folder and run the mongod.exe file.
  2. Navigate to your mongodb bin folder via Command prompt and start mongo by typing "mongo"

Removing u in list

arr = [str(r) for r in arr]

This basically converts all your elements in string. Hence removes the encoding. Hence the u which represents encoding gets removed Will do the work easily and efficiently

Java error: Comparison method violates its general contract

It also has something to do with the version of JDK. If it does well in JDK6, maybe it will have the problem in JDK 7 described by you, because the implementation method in jdk 7 has been changed.

Look at this:

Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behaviour.

I don't know the exact reason. However, if you add the code before you use sort. It will be OK.

System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

MVC 4 client side validation not working

I had an issue with validation, the form posts then it validates,

This Doesn't work with jquery cdn

    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

This Works without jquery cdn

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hope helps someone.

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):

>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0    False
1     True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  res_values = method(rvalues)
0    False
1    False

I think with pandas 1.0 they really want you to use the new 'string' datatype which allows for pd.NA values:

>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0    False
1    False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0    <NA>
1    <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0    False
1    False

Don't love at which point they tinkered with every-day functionality such as boolean indexing.

Custom header to HttpClient request

I have found the answer to my question.

client.DefaultRequestHeaders.Add("X-Version","1");

That should add a custom header to your request

Adding a right click menu to an item

Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.

cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

How to print a string at a fixed width?

format is definitely the most elegant way, but afaik you can't use that with python's logging module, so here's how you can do it using the % formatting:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

Here, the - indicates left-alignment, and the number before s indicates the fixed width.

Some sample output:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Why am I getting error CS0246: The type or namespace name could not be found?

This usually happens to me when I have a using statement but have forgotten to reference the assembly that defines the namespace.

But in your case, as the namespace is defined in a file in your project, you have forgotten to tell the compiler about the snarlnetwork.cs file.

See csc compiler examples

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

Git commit date

You can use the git show command.

To get the last commit date from git repository in a long(Unix epoch timestamp):

  • Command: git show -s --format=%ct
  • Result: 1605103148

Note: You can visit the git-show documentation to get a more detailed description of the options.

How to set env variable in Jupyter notebook

A gotcha I ran into: The following two commands are equivalent. Note the first cannot use quotes. Somewhat counterintuitively, quoting the string when using %env VAR ... will result in the quotes being included as part of the variable's value, which is probably not what you want.

%env MYPATH=C:/Folder Name/file.txt

and

import os
os.environ['MYPATH'] = "C:/Folder Name/file.txt"

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

Local and global temporary tables in SQL Server

It is worth mentioning that there is also: database scoped global temporary tables(currently supported only by Azure SQL Database).

Global temporary tables for SQL Server (initiated with ## table name) are stored in tempdb and shared among all users’ sessions across the whole SQL Server instance.

Azure SQL Database supports global temporary tables that are also stored in tempdb and scoped to the database level. This means that global temporary tables are shared for all users’ sessions within the same Azure SQL Database. User sessions from other databases cannot access global temporary tables.

-- Session A creates a global temp table ##test in Azure SQL Database testdb1
-- and adds 1 row
CREATE TABLE ##test ( a int, b int);
INSERT INTO ##test values (1,1);

-- Session B connects to Azure SQL Database testdb1 
-- and can access table ##test created by session A
SELECT * FROM ##test
---Results
1,1

-- Session C connects to another database in Azure SQL Database testdb2 
-- and wants to access ##test created in testdb1.
-- This select fails due to the database scope for the global temp tables 
SELECT * FROM ##test
---Results
Msg 208, Level 16, State 0, Line 1
Invalid object name '##test'

ALTER DATABASE SCOPED CONFIGURATION

GLOBAL_TEMPORARY_TABLE_AUTODROP = { ON | OFF }

APPLIES TO: Azure SQL Database (feature is in public preview)

Allows setting the auto-drop functionality for global temporary tables. The default is ON, which means that the global temporary tables are automatically dropped when not in use by any session. When set to OFF, global temporary tables need to be explicitly dropped using a DROP TABLE statement or will be automatically dropped on server restart.

With Azure SQL Database single databases and elastic pools, this option can be set in the individual user databases of the SQL Database server. In SQL Server and Azure SQL Database managed instance, this option is set in TempDB and the setting of the individual user databases has no effect.

Why is there no String.Empty in Java?

Don't just say "memory pool of strings is reused in the literal form, case closed". What compilers do under the hood is not the point here. The question is reasonable, specially given the number of up-votes it received.

It's about the symmetry, without it APIs are harder to use for humans. Early Java SDKs notoriously ignored the rule and now it's kind of too late. Here are a few examples on top of my head, feel free to chip in your "favorite" example:

  • BigDecimal.ZERO, but no AbstractCollection.EMPTY, String.EMPTY
  • Array.length but List.size()
  • List.add(), Set.add() but Map.put(), ByteBuffer.put() and let's not forget StringBuilder.append(), Stack.push()

How to vertically align into the center of the content of a div with defined width/height?

I found this solution in this article

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

It work like a charm if the height of element is not fixed.

How to implement the ReLU function in Numpy

EDIT As jirassimok has mentioned below my function will change the data in place, after that it runs a lot faster in timeit. This causes the good results. It's some kind of cheating. Sorry for your inconvenience.

I found a faster method for ReLU with numpy. You can use the fancy index feature of numpy as well.

fancy index:

20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

>>> x = np.random.random((5,5)) - 0.5 
>>> x
array([[-0.21444316, -0.05676216,  0.43956365, -0.30788116, -0.19952038],
       [-0.43062223,  0.12144647, -0.05698369, -0.32187085,  0.24901568],
       [ 0.06785385, -0.43476031, -0.0735933 ,  0.3736868 ,  0.24832288],
       [ 0.47085262, -0.06379623,  0.46904916, -0.29421609, -0.15091168],
       [ 0.08381359, -0.25068492, -0.25733763, -0.1852205 , -0.42816953]])
>>> x[x<0]=0
>>> x
array([[ 0.        ,  0.        ,  0.43956365,  0.        ,  0.        ],
       [ 0.        ,  0.12144647,  0.        ,  0.        ,  0.24901568],
       [ 0.06785385,  0.        ,  0.        ,  0.3736868 ,  0.24832288],
       [ 0.47085262,  0.        ,  0.46904916,  0.        ,  0.        ],
       [ 0.08381359,  0.        ,  0.        ,  0.        ,  0.        ]])

Here is my benchmark:

import numpy as np
x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)
print("max inplace method:")
%timeit -n10 np.maximum(x, 0,x)
print("multiplication method:")
%timeit -n10 x * (x > 0)
print("abs method:")
%timeit -n10 (abs(x) + x) / 2
print("fancy index:")
%timeit -n10 x[x<0] =0

max method:
241 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
max inplace method:
38.5 ms ± 4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
multiplication method:
162 ms ± 3.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
abs method:
181 ms ± 4.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
fancy index:
20.3 ms ± 272 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Use sudo with password as parameter

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

How to delete mysql database through shell command

If you are tired of typing your password, create a (chmod 600) file ~/.my.cnf, and put in it:

[client]
user = "you"
password = "your-password"

For the sake of conversation:

echo 'DROP DATABASE foo;' | mysql

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

Difference between "include" and "require" in php

You find the differences explained in the detailed PHP manual on the page of require:

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See @efritz's answer for an example

How to uninstall Golang?

In MacOS, you can just do it with brew:

brew uninstall go
brew install go
brew upgrade go

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

Android add placeholder text to EditText

You have to use the android:hint attribute

<EditText
android:id="@+id/message"
android:hint="<<Your placeholder>>"
/>

In Android Studio, you can switch from XML -> Design View and click on the Component in the layout, the EditText field in this case. This will show all the applicable attributes for that GUI component. This will be handy when you don't know about all the attributes that are there.

You would be surprised to see that EditText has more than 140 attributes for customization.

How to do associative array/hashing in JavaScript

Since every object in JavaScript behaves like - and is generally implemented as - a hashtable, I just go with that...

var hashSweetHashTable = {};

How to export settings?

Enable portable mode: https://code.visualstudio.com/docs/editor/portable

Summary: Portable Mode instructs VSC to store all its configuration and plugins in a specific directory (called data/ in Windows and Linux and code-portable-data in MacOS). At any time you could copy the data directory and copy it on another installation.

How to set the timezone in Django?

I found this question looking to change the timezone in my Django project's settings.py file to the United Kingdom.

Using the tz database in jfs' solution I found the answer:

    TIME_ZONE = 'Europe/London'

Adding a Scrollable JTextArea (Java)

A scroll pane is a container which contains another component. You can't add your text area to two different scroll panes. The scroll pane takes care of the horizontal and vertical scroll bars.

And if you never add the scroll pane to the frame, it will never be visible.

Read the swing tutorial about scroll panes.

What is a unix command for deleting the first N characters of a line?

You can use cut:

cut -c N- file.txt > new_file.txt

-c: characters

file.txt: input file

new_file.txt: output file

N-: Characters from N to end to be cut and output to the new file.

Can also have other args like: 'N' , 'N-M', '-M' meaning nth character, nth to mth character, first to mth character respectively.

This will perform the operation to each line of the input file.

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Undefined variable: $_SESSION

Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start being on (defaults to off)

If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):

/etc/php.d/my-new-file.ini :

session.auto_start = 1

(This is correct for CentOS 8, adjust for your OS/packaging)

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

CodeIgniter Active Record - Get number of returned rows

function getCount(){
    return $this->db->get('table_name')->num_rows();
}

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

How to emulate GPS location in the Android Emulator?

I was trying to set the geo fix through adb for many points and could not get my app to see any GPS data. But when I tried opening DDMS, selecting my app's process and sending coordinates through the emulator control tab it worked right away.

How to have a default option in Angular.js select box

If you have some thing instead of just init the date part, you can use ng-init() by declare it in your controller, and use it in the top of your HTML. This function will work like a constructor for your controller, and you can initiate your variables there.

angular.module('myApp', [])
 .controller('myController', ['$scope', ($scope) => {
   $scope.allOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }
   ];
   $scope.myInit = () => {
      $scope.userSelected = 'apple'
      // Other initiations can goes here..
   }
}]);


<body ng-app="myApp">
  <div ng-controller="myController" ng-init="init()">
    <select ng-model="userSelected" ng-options="option.value as option.name for option in allOptions"></select>
   </div>
</body>

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

Python class inherits object

Yes, it's historical. Without it, it creates an old-style class.

If you use type() on an old-style object, you just get "instance". On a new-style object you get its class.

How to move an entire div element up x pixels?

$('#div_id').css({marginTop: '-=15px'});

This will alter the css for the element with the id "div_id"

To get the effect you want I recommend adding the code above to a callback function in your animation (that way the div will be moved up after the animation is complete):

$('#div_id').animate({...}, function () {
    $('#div_id').css({marginTop: '-=15px'});
});

And of course you could animate the change in margin like so:

$('#div_id').animate({marginTop: '-=15px'});

Here are the docs for .css() in jQuery: http://api.jquery.com/css/

And here are the docs for .animate() in jQuery: http://api.jquery.com/animate/

Password encryption at client side

This sort of protection is normally provided by using HTTPS, so that all communication between the web server and the client is encrypted.

The exact instructions on how to achieve this will depend on your web server.

The Apache documentation has a SSL Configuration HOW-TO guide that may be of some help. (thanks to user G. Qyy for the link)

Convert a Pandas DataFrame to a dictionary

Should a dictionary like:

{'red': '0.500', 'yellow': '0.250, 'blue': '0.125'}

be required out of a dataframe like:

        a      b
0     red  0.500
1  yellow  0.250
2    blue  0.125

simplest way would be to do:

dict(df.values)

working snippet below:

import pandas as pd
df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
dict(df.values)

SQL Server - transactions roll back on error?

From MDSN article, Controlling Transactions (Database Engine).

If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the Database Engine is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For more information, see SET XACT_ABORT (Transact-SQL).

In your case it will rollback the complete transaction when any of inserts fail.

Concatenate two string literals

In case 1, because of order of operations you get:

(hello + ", world") + "!" which resolves to hello + "!" and finally to hello

In case 2, as James noted, you get:

("Hello" + ", world") + exclam which is the concat of 2 string literals.

Hope it's clear :)

Unix epoch time to Java Date object

Hum.... if I am not mistaken, the UNIX Epoch time is actually the same thing as

System.currentTimeMillis()

So writing

try {
    Date expiry = new Date(Long.parseLong(date));
}
catch(NumberFormatException e) {
    // ...
}

should work (and be much faster that date parsing)

How to set Internet options for Android emulator?

If someone have a Internet Permission in AndroidManifest and still have a problem with Internet Connection, maybe that will be helpful: Android - Fixing the no internet connection issue on emulator.

I followed steps from that website, and everything works for me. The most important:

  • Configuring the proxy server on the emulator
  • Incorrect DNS Used by the Emulator

That is my first post, so I hope it will be helpful.

How does one parse XML files?

You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.

Regex allow digits and a single dot

\d*\.\d*

Explanation:

\d* - any number of digits

\. - a dot

\d* - more digits.

This will match 123.456, .123, 123., but not 123

If you want the dot to be optional, in most languages (don't know about jquery) you can use

\d*\.?\d*

Randomize numbers with jQuery?

Javascript has a random() available. Take a look at Math.random().

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

Whether or not the "date" '0000-00-00" is a valid "date" is irrelevant to the question. "Just change the database" is seldom a viable solution.

Facts:

  • MySQL allows a date with the value of zeros.
  • This "feature" enjoys widespread use with other languages.

So, if I "just change the database", thousands of lines of PHP code will break.

Java programmers need to accept the MySQL zero-date and they need to put a zero date back into the database, when other languages rely on this "feature".

A programmer connecting to MySQL needs to handle null and 0000-00-00 as well as valid dates. Changing 0000-00-00 to null is not a viable option, because then you can no longer determine if the date was expected to be 0000-00-00 for writing back to the database.

For 0000-00-00, I suggest checking the date value as a string, then changing it to ("y",1), or ("yyyy-MM-dd",0001-01-01), or into any invalid MySQL date (less than year 1000, iirc). MySQL has another "feature": low dates are automatically converted to 0000-00-00.

I realize my suggestion is a kludge. But so is MySQL's date handling. And two kludges don't make it right. The fact of the matter is, many programmers will have to handle MySQL zero-dates forever.

Jquery UI Datepicker not displaying

This is a slightly different problem. With me the date picker would display but the css was not loading.

I fixed it by: Reload the theme (go to jquery ui css, line 43 and copy the url there to edit your themeroller theme) > Resave without the advanced options > Replace old files > Try not to change the urls and see if that helps as well.

SQL Query - Change date format in query to DD/MM/YYYY

If you have a Date (or Datetime) column, look at http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

 SELECT DATE_FORMAT(datecolumn,'%d/%m/%Y') FROM ...

Should do the job for MySQL, for SqlServer I'm sure there is an analog function. If you have a VARCHAR column, you might have at first to convert it to a date, see STR_TO_DATE for MySQL.

How to insert an element after another element in JavaScript without using a library?

a robust implementation of insertAfter.

// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
  function isNode(node) {
    return node instanceof Node;
  }

  if(arguments.length < 2){
    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
  }

  if(isNode(newNode)){
    if(referenceNode === null || referenceNode === undefined){
      return this.insertBefore(newNode, referenceNode);
    }

    if(isNode(referenceNode)){
      return this.insertBefore(newNode, referenceNode.nextSibling);
    }

    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
  }

  throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};

Android transparent status bar and actionbar

Just add these lines of code to your activity/fragment java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

Launching a website via windows commandline

Ok, The Windows 10 BatchFile is done works just like I had hoped. First press the windows key and R. Type mmc and Enter. In File Add SnapIn>Got to a specific Website and add it to the list. Press OK in the tab, and on the left side console root menu double click your site. Once it opens Add it to favourites. That should place it in C:\Users\user\AppData\Roaming\Microsoft\StartMenu\Programs\Windows Administrative Tools. I made a shortcut of this to a folder on the desktop. Right click the Shortcut and view the properties. In the Shortcut tab of the Properties click advanced and check the Run as Administrator. The Start in Location is also on the Shortcuts Tab you can add that to your batch file if you need. The Batch I made is as follows

@echo off
title Manage SiteEnviro
color 0a
:Clock
cls
echo Date:%date% Time:%time%
pause
cls
c:\WINDOWS\System32\netstat
c:\WINDOWS\System32\netstat -an
goto Greeting

:Greeting
cls
echo Open ShellSite
pause
cls
goto Manage SiteEnviro

:Manage SiteEnviro
"C:\Users\user\AppData\Roaming\Microsoft\Start Menu\Programs\Administrative Tools\YourCustomSavedMMC.msc"

You need to make a shortcut when you save this as a bat file and in the properties>shortcuts>advanced enable administrator access, can also set a keybind there and change the icon if you like. I probably did not need :Clock. The netstat commands can change to setting a hosted network or anything you want including nothing. Can Canscade websites in 1 mmc console and have more than 1 favourite added into the batch file.

How to start a stopped Docker container with a different command?

My Problem:

  • I started a container with docker run <IMAGE_NAME>
  • And then added some files to this container
  • Then I closed the container and tried to start it again withe same command as above.
  • But when I checked the new files, they were missing
  • when I run docker ps -a I could see two containers.
  • That means every time I was running docker run <IMAGE_NAME> command, new image was getting created

Solution: To work on the same container you created in the first place run follow these steps

  • docker ps to get container of your container
  • docker container start <CONTAINER_ID> to start existing container
  • Then you can continue from where you left. e.g. docker exec -it <CONTAINER_ID> /bin/bash
  • You can then decide to create a new image out of it

Printing one character at a time from a string, using the while loop

I'm quite sure, that the internet is full of python while-loops, but one example:

i=0

while i < len(text):
    print text[i]
    i += 1

How do I run a shell script without using "sh" or "bash" commands?

Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.

Just make sure to add Shebang (#!/bin/bash) line at the starting of your script and make the script executable(using chmod +x <File Name>).

How can I sort an ArrayList of Strings in Java?

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

Query to check index on a table

Here is what I used for TSQL which took care of the problem that my table name could contain the schema name and possibly the database name:

DECLARE @THETABLE varchar(100);
SET @THETABLE = 'theschema.thetable';
select i.*
  from sys.indexes i
 where i.object_id = OBJECT_ID(@THETABLE)
   and i.name is not NULL;

The use case for this is that I wanted the list of indexes for a named table so I could write a procedure that would dynamically compress all indexes on a table.

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

Maximum concurrent connections to MySQL

As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_user_connections

 maximum range: 4,294,967,295  (e.g. 2**32 - 1)

You'd probably run out of memory, file handles, and network sockets, on your server long before you got anywhere close to that limit.

How to display pdf in php

Download PDFObject library from https://pdfobject.com/ and check the below code: I hope it will work you.

<!DOCTYPE html>
<html>
<head>
    <title>Pdf Read</title>
    <style>
          .pdfobject-container { height: 500px;}
          .pdfobject { border: 1px solid #666; }
   </style>
   <script src="pdfobject.min.js"></script>
</head>
<body>
        <div id="example1"></div>
        <script>PDFObject.embed("pdfread.pdf", "#example1");</script>
</body>
</html>

Add zero-padding to a string

myInt.ToString("D4");

how to set value of a input hidden field through javascript?

Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if statements that are not allowing your scripts to execute.

How to use bitmask?

Bitmasks are used when you want to encode multiple layers of information in a single number.

So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.

rwx
---
110

110 in base 2 translates to 6 in base 10.

So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.

Pseudocode:

PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1

user_permissions = 6

if (user_permissions & PERM_READ == TRUE) then
  // this will be reached, as 6 & 4 is true
fi

You need a working understanding of binary representation of numbers and logical operators to understand bit fields.

How to replace negative numbers in Pandas Data Frame by zero

Another succinct way of doing this is pandas.DataFrame.clip.

For example:

import pandas as pd

In [20]: df = pd.DataFrame({'a': [-1, 100, -2]})

In [21]: df
Out[21]: 
     a
0   -1
1  100
2   -2

In [22]: df.clip(lower=0)
Out[22]: 
     a
0    0
1  100
2    0

There's also df.clip_lower(0).

Are the decimal places in a CSS width respected?

They seem to round up the values to the closest integer; but Iam seeing inconsistency in chrome,safari and firefox.

For e.g if 33.3% converts to 420.945px

chrome and firexfox show it as 421px. while safari shows its as 420px.

This seems like chrome and firefox follow the floor and ceil logic while safari doesn't. This page seems to discuss the same problem

http://ejohn.org/blog/sub-pixel-problems-in-css/

Call apply-like function on each row of dataframe with multiple arguments from each row

Here is an alternate approach. It is more intuitive.

One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data

operations on columns are possible still for dataframes:

as.data.frame(lapply(df, myFunctionForColumn()))

To operate on rows, we make the transpose first.

tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))

The downside is that I believe R will make a copy of your data table. Which could be a memory issue. (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)

Also, a related question, is how to operate on each individual cell in a dataframe.

newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))

Vertically align text within a div

Create a container for your text content, a span perhaps.

_x000D_
_x000D_
#column-content {_x000D_
  display: inline-block;_x000D_
}_x000D_
img {_x000D_
  vertical-align: middle;_x000D_
}_x000D_
span {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
}_x000D_
_x000D_
/* for visual purposes */_x000D_
#column-content {_x000D_
  border: 1px solid red;_x000D_
  position: relative;_x000D_
}
_x000D_
<div id="column-content">_x000D_
_x000D_
  <img src="http://i.imgur.com/WxW4B.png">_x000D_
  <span><strong>1234</strong>_x000D_
    yet another text content that should be centered vertically</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

After updating Entity Framework model, Visual Studio does not see changes

I searched for this answer because I had a similar situation in VS2013. In my case, I found that a simple "Clean Solution" cleared out all the old definitions.

How to check if IsNumeric

There's the TryParse method, which returns a bool indicating if the conversion was successful.

How to convert UTF8 string to byte array?

You can save a string raw as is by using FileReader.

Save the string in a blob and call readAsArrayBuffer(). Then the onload-event results an arraybuffer, which can converted in a Uint8Array. Unfortunately this call is asynchronous.

This little function will help you:

function stringToBytes(str)
{
    let reader = new FileReader();
    let done = () => {};

    reader.onload = event =>
    {
        done(new Uint8Array(event.target.result), str);
    };
    reader.readAsArrayBuffer(new Blob([str], { type: "application/octet-stream" }));

    return { done: callback => { done = callback; } };
}

Call it like this:

stringToBytes("\u{1f4a9}").done(bytes =>
{
    console.log(bytes);
});

output: [240, 159, 146, 169]

explanation:

JavaScript use UTF-16 and surrogate-pairs to store unicode characters in memory. To save unicode character in raw binary byte streams an encoding is necessary. Usually and in the most case, UTF-8 is used for this. If you not use an enconding you can't save unicode character, just ASCII up to 0x7f.

FileReader.readAsArrayBuffer() uses UTF-8.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Webforms' or

Could not load file or assembly 'Microsoft.ReportViewer.Common'

This issue occured for me in Visual studio 2015.

Reason:

the reference for Microsoft.ReportViewer.Webforms dll is missing.

Possible Fix

Step1:

To add "Microsoft.ReportViewer.Webforms.dll" to the solution.

Navigate to Nuget Package Manager Console as

"Tools-->NugetPackageManager-->Package Manager Console".

Then enter the following command in console as below

PM>Install-Package Microsoft.ReportViewer.Runtime.WebForms

Then it will install the Reportviewer.webforms dll in "..\packages\Microsoft.ReportViewer.Runtime.WebForms.12.0.2402.15\lib" (Your project folder path)

and ReportViewer.Runtime.Common dll in "..\packages\Microsoft.ReportViewer.Runtime.Common.12.0.2402.15\lib". (Your project folder path)

Step2:-

Remove the existing reference of "Microsoft.ReportViewer.WebForms". we need to refer these dll files in our Solution as "Right click Solution >References-->Add reference-->browse ". Add both the dll files from the above paths.

Step3:

Change the web.Config File to point out to Visual Studio 2015. comment out both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common version 11.0.0.0 and Uncomment both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common Version=12.0.0.0. as attached in screenshot.

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

How can I create a Java method that accepts a variable number of arguments?

This is known as varargs see the link here for more details

In past java releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:

Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};
    String result = MessageFormat.format(
        "At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

public static String format(String pattern,
                            Object... arguments);

How do you read scanf until EOF in C?

Try:

while(scanf("%15s", words) != EOF)

You need to compare scanf output with EOF

Since you are specifying a width of 15 in the format string, you'll read at most 15 char. So the words char array should be of size 16 ( 15 +1 for null char). So declare it as:

char words[16];

Why doesn't Java allow overriding of static methods?

Actually we were wrong.
Despite Java doesn't allow you to override static methods by default, if you look thoroughly through documentation of Class and Method classes in Java, you can still find a way to emulate static methods overriding by following workaround:

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;

class RegularEmployee {

    private BigDecimal salary = BigDecimal.ONE;

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".02");
    }
    public BigDecimal calculateBonus() {
        return salary.multiply(this.getBonusMultiplier());
    }
    public BigDecimal calculateOverridenBonus() {
        try {
            // System.out.println(this.getClass().getDeclaredMethod(
            // "getBonusMultiplier").toString());
            try {
                return salary.multiply((BigDecimal) this.getClass()
                    .getDeclaredMethod("getBonusMultiplier").invoke(this));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    // ... presumably lots of other code ...
}

final class SpecialEmployee extends RegularEmployee {

    public static BigDecimal getBonusMultiplier() {
        return new BigDecimal(".03");
    }
}

public class StaticTestCoolMain {

    static public void main(String[] args) {
        RegularEmployee Alan = new RegularEmployee();
        System.out.println(Alan.calculateBonus());
        System.out.println(Alan.calculateOverridenBonus());
        SpecialEmployee Bob = new SpecialEmployee();
        System.out.println(Bob.calculateBonus());
        System.out.println(Bob.calculateOverridenBonus());
    }
}

Resulting output:

0.02
0.02
0.02
0.03

what we were trying to achieve :)

Even if we declare third variable Carl as RegularEmployee and assign to it instance of SpecialEmployee, we will still have call of RegularEmployee method in first case and call of SpecialEmployee method in second case

RegularEmployee Carl = new SpecialEmployee();

System.out.println(Carl.calculateBonus());
System.out.println(Carl.calculateOverridenBonus());

just look at output console:

0.02
0.03

;)

Cannot create PoolableConnectionFactory

The problem could be due to too many users accessing the db at the same time. Either increase number of users that can concurrently access the db or kick out existing users (or apps). Use "Show processlist;" in the host DB to check connected users;

I came across another reason, catalina.policy file, could prohibit accessing specific IP/PORT

Get only records created today in laravel

$records = User::where('created_at' = CURDATE())->GET()); print($records);

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Just wanted to add this little snippet which works beautifully for me.

INSERT INTO your_target_table SELECT * FROM your_rescource_table WHERE id = 18;

And while I'm at it give a big shout out to Sequel Pro, if you're not using it I highly recommend downloading it...makes life so much easier

What is "not assignable to parameter of type never" error in typescript?

This seems to be a recent regression or some strange behavior in typescript. If you have the code:

const result = []

Usually it would be treated as if you wrote:

const result:any[] = []

however, if you have both noImplicitAny FALSE, AND strictNullChecks TRUE in your tsconfig, it is treated as:

const result:never[] = []

This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny actually restores the use of any without any warnings??

When you truly have an array of any, you shouldn't need to indicate it with extra code.

Argument Exception "Item with Same Key has already been added"

As others have said, you are adding the same key more than once. If this is a NOT a valid scenario, then check Jdinklage Morgoone's answer (which only saves the first value found for a key), or, consider this workaround (which only saves the last value found for a key):

// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];

Otherwise, if it is valid to have multiple values for a single key, then you should consider storing your values in a List<string> for each string key.

For example:

var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();

foreach (string line in rct3Lines)
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        // No items for this key have been added, so create a new list
        // for the value with item[1] as the only item in the list
        rct3Features.Add(items[0], new List<string> { items[1] });
    }
    else
    {
        // This key already exists, so add item[1] to the existing list value
        rct3Features[items[0]].Add(items[1]);
    }
}

// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
    Console.WriteLine("The Key: {0} has values:", item.Key);
    foreach (string value in item.Value)
    {
        Console.WriteLine(" - {0}", value);
    }
}

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

Delete all data in SQL Server database

Yes, it is possible to delete with a single line of code

SELECT 'TRUNCATE TABLE ' + d.NAME + ';' 
FROM   sys.tables d 
WHERE  type = 'U' 

MySQL: Can't create table (errno: 150)

If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors

create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;


create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;

How to make pylab.savefig() save image for 'maximized' window instead of default size

I think you need to specify a different resolution when saving the figure to a file:

fig = matplotlib.pyplot.figure()
# generate your plot
fig.savefig("myfig.png",dpi=600)

Specifying a large dpi value should have a similar effect as maximizing the GUI window.

How do you clone an Array of Objects in Javascript?

The issue with your shallow copy is that all the objects aren't cloned. While the references to each object are unique in each array, once you ultimately grab onto it you're dealing with the same object as before. There is nothing wrong with the way you cloned it... the same result would occur using Array.slice().

The reason your deep copy is having problems is because you're ending up with circular object references. Deep will go as deep as it can go, and if you've got a circle, it'll keep going infinitely until the browser faints.

If the data structure cannot be represented as a directed acyclic graph, then I'm not sure you're going to be able to find an all-purpose method for deep cloning. Cyclic graphs provide many tricky corner cases, and since it's not a common operation I doubt anyone has written a full solution (if it's even possible - it might not be! But I have no time to try to write a rigorous proof now.). I found some good comments on the issue on this page.

If you need a deep copy of an Array of Objects with circular references I believe you're going to have to code your own method to handle your specialized data structure, such that it is a multi-pass clone:

  1. On round one, make a clone of all objects that don't reference other objects in the array. Keep a track of each object's origins.
  2. On round two, link the objects together.

How do I change the background color with JavaScript?

I would suggest the following code:

<div id="example" onClick="colorize()">Click on this text to change the
background color</div>
<script type='text/javascript'>
function colorize() {
var element = document.getElementById("example");
element.style.backgroundColor='#800';
element.style.color='white';
element.style.textAlign='center';
}
</script>

How to create a folder with name as current date in batch (.bat) files

If your locale has date format "DDMMYYYY" you'll have to set it this way:

set datestr=%date:~-4,4%%date:~3,2%%date:~-10,2%
mkdir %datestr%

How to check if a variable exists in a FreeMarker template?

To check if the value exists:

[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>

Initializing a struct to 0

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:
C and C++ : Partial initialization of automatic structure

Disable Transaction Log

If this is only for dev machines in order to save space then just go with simple recovery mode and you’ll be doing fine.

On production machines though I’d strongly recommend that you keep the databases in full recovery mode. This will ensure you can do point in time recovery if needed.

Also – having databases in full recovery mode can help you to undo accidental updates and deletes by reading transaction log. See below or more details.

How can I rollback an UPDATE query in SQL server 2005?

Read the log file (*.LDF) in sql server 2008

If space is an issue on production machines then just create frequent transaction log backups.

Show constraints on tables command

There is also a tool that oracle made called mysqlshow

If you run it with the --k keys $table_name option it will display the keys.

SYNOPSIS
   mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
·   --keys, -k
   Show table indexes.

example:

?-?  mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database  Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field           | Type             | Collation          | Null | Key | Default | Extra          | Privileges                      | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id              | int(10) unsigned |                    | NO   | PRI |         | auto_increment | select,insert,update,references |         |
| token           | text             | utf8mb4_unicode_ci | NO   |     |         |                | select,insert,update,references |         |
| user_id         | int(10) unsigned |                    | NO   | MUL |         |                | select,insert,update,references |         |
| expires_in      | datetime         |                    | YES  |     |         |                | select,insert,update,references |         |
| created_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
| updated_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table  | Non_unique | Key_name                 | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0          | PRIMARY                  | 1            | id          | A         | 2           |          |        |      | BTREE      |         |               |
| tokens | 1          | tokens_user_id_foreign   | 1            | user_id     | A         | 2           |          |        |      | BTREE      |         |               |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

How to split csv whose columns may contain ,

With Cinchoo ETL - an open source library, it can automatically handles columns values containing separators.

string csv = @"2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,""Corvallis, OR"",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

using (var p = ChoCSVReader.LoadText(csv)
    )
{
    Console.WriteLine(p.Dump());
}

Output:

Key: Column1 [Type: String]
Value: 2
Key: Column2 [Type: String]
Value: 1016
Key: Column3 [Type: String]
Value: 7/31/2008 14:22
Key: Column4 [Type: String]
Value: Geoff Dalgas
Key: Column5 [Type: String]
Value: 6/5/2011 22:21
Key: Column6 [Type: String]
Value: http://stackoverflow.com
Key: Column7 [Type: String]
Value: Corvallis, OR
Key: Column8 [Type: String]
Value: 7679
Key: Column9 [Type: String]
Value: 351
Key: Column10 [Type: String]
Value: 81
Key: Column11 [Type: String]
Value: b437f461b3fd27387c5d8ab47a293d35
Key: Column12 [Type: String]
Value: 34

For more information, please visit codeproject article.

Hope it helps.

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

When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.

enter image description here

Installing Bower on Ubuntu

At Least from Ubuntu 12.04, an old version (0.6.x) of Node is in the standard repository. To install, just run:

sudo apt-get install nodejs

NPM comes with latest version of nodejs. Once you have that, then run

sudo npm install bower -g

Should be good to go after that. You may need to run some updates, but it should be fairly straight forward.

How to get current date in jquery?

Since the question is tagged as JQuery:

If you are also using JQuery UI you can use $.datepicker.formatDate():

$.datepicker.formatDate('yy/mm/dd', new Date());

See this demo.

Django Forms: if not valid, show form with error message

@AamirAdnan's answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

In c++ what does a tilde "~" before a function name signify?

This is a destructor. It's called when the object is destroyed (out of life scope or deleted).

To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.

How to select a CRAN mirror in R

You should either get a window with a list of repositories or a text menu with some options. But if that is not appearing, you can always specify the mirror from where to download the packages yourself by using repos parameter. By doing that, R will not ask you anymore about the repository. Example:

install.packages('RMySQL', repos='http://cran.us.r-project.org')

Here you have a list of mirrors for R.

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

Setting the Vim background colors

supplement of windows

gvim version: 8.2

location of .gvimrc: %userprofile%/.gvimrc

" .gvimrc
colorscheme darkblue

Which color is allows me to choose?

Find your install directory and go to the directory of colors. in my case is: %PROGRAMFILES(X86)%\Vim\vim82\colors

blue.vim
darkblue.vim
slate.vim
...
README.txt

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

How can I get the current screen orientation?

In case anyone would like to obtain meaningful orientation description (like that passed to onConfigurationChanged(..) with those reverseLandscape, sensorLandscape and so on), simply use getRequestedOrientation()

GridView Hide Column by code

GridView.Columns.Count will always be 0 when your GridView has its AutoGenerateColumns property set to true (default is true).

You can explicitly declare your columns and set the AutoGenerateColumns property to false, or you can use this in your codebehind:

GridView.Rows[0].Cells.Count

to get the column count once your GridView data has been bound, or this:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[index].Visible = false;
}

to set a column invisible using your GridView's RowDataBound event.

Cannot hide status bar in iOS7

I had to do both changes below to hide the status bar:

Add this code to the view controller where you want to hide the status bar:

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

Add this to your .plist file (go to 'info' in your application settings)

View controller-based status bar appearance --- NO

Then you can call this line to hide the status bar:

[[UIApplication sharedApplication] setStatusBarHidden:YES];