Programs & Examples On #Yarv

YARV (Yet another Ruby VM) is a bytecode interpreter for the Ruby programming language developed by Koichi Sasada and has become the official Ruby interpreter for Ruby 1.9.

Alternative to itoa() for converting integer to string C++?

Note that all of the stringstream methods may involve locking around the use of the locale object for formatting. This may be something to be wary of if you're using this conversion from multiple threads...

See here for more. Convert a number to a string with specified length in C++

Edit a specific Line of a Text File in C#

the easiest way is :

static void lineChanger(string newText, string fileName, int line_to_edit)
{
     string[] arrLine = File.ReadAllLines(fileName);
     arrLine[line_to_edit - 1] = newText;
     File.WriteAllLines(fileName, arrLine);
}

usage :

lineChanger("new content for this line" , "sample.text" , 34);

How to sort an object array by date property?

@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b){return a.getTime() - b.getTime()});

Using the arrow function way

array.sort((a,b)=>a.getTime()-b.getTime());

found here: Sort date in Javascript

Laravel form html with PUT method for PUT routes

Is very easy, you just need to use method_field('PUT') like this:

HTML:

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

or

<form action="{{ route('route_name') }}" method="post">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Regards!

Java: Check if command line arguments are null

The arguments can never be null. They just wont exist.

In other words, what you need to do is check the length of your arguments.

public static void main(String[] args)
{
    // Check how many arguments were passed in
    if(args.length == 0)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}

Insert image after each list item

Try this:

ul li a:after {
    display: block;
    content: "";
    width: 3px;
    height: 5px;
    background: transparent url('../images/small_triangle.png') no-repeat;
}

You need the content: ""; declaration to give your generated element content, even if that content is "nothing".

Also, I fixed the syntax/ordering of your background declaration.

How does one remove a Docker image?

Delete all of them using

Step 1: Kill all containers

for i in `sudo docker ps -a | awk '{ print $1 }'`; do sudo docker kill $i ; done

Step 2: RM them first

for i in `sudo docker ps -a | awk '{ print $1 }'`; do sudo docker rm $i ; done

Step 3: Delete the images using force

for i in `sudo docker images | awk '{ print $3}'`; do  sudo docker rmi --force $i ; done

Use the step 1 in case you are getting error saying it cant be deleted owing to child dependencies

SQL Server IN vs. EXISTS Performance

The execution plans are typically going to be identical in these cases, but until you see how the optimizer factors in all the other aspects of indexes etc., you really will never know.

"Error: Main method not found in class MyClass, please define the main method as..."

Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main method:

For example, in the file Foo.java

public class Foo {
    public static void main(final String args[]) {
        System.out.println("hello");
    }
}

This program should compile and run no problem - if main was called something else, or was not static, it would generate the error you experienced.

Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main, which is passed the parameter args[] containing the command line arguments. This method is equivalent to int main(int argc, char** argv) in C language.

Two statements next to curly brace in an equation

That can be achieve in plain LaTeX without any specific package.

\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
  \left\{
    \begin{array}{l}
      0\\
      1
    \end{array}
  \right.
\end{math}
\end{document}

This code produces something which looks what you seems to need.

curly braces in front of two lines

The same example as in the @Tombart can be obtained with similar code.

\documentclass{article}

\begin{document}

\begin{math}
  f(x)=\left\{
    \begin{array}{ll}
      1, & \mbox{if $x<0$}.\\
      0, & \mbox{otherwise}.
    \end{array}
  \right.
\end{math}

\end{document}

This code produces very similar results.

enter image description here

jquery: change the URL address without redirecting?

You can't do what you ask (and the linked site does not do exactly that either).

You can, however, modify the part of the url after the # sign, which is called the fragment, like this:

window.location.hash = 'something';

Fragments do not get sent to the server (so, for example, Google itself cannot tell the difference between http://www.google.com/ and http://www.google.com/#something), but they can be read by Javascript on your page. In turn, this Javascript can decide to perform a different AJAX request based on the value of the fragment, which is how the site you linked to probably does it.

GET and POST methods with the same Action name in the same Controller

Today I was checking some resources about the same question and I got an example very interesting.

It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:

@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}

The action:

[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}

By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.

When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


What is the best way to call a script from another script?

Add this to your python script.

import os
os.system("exec /path/to/another/script")

This executes that command as if it were typed into the shell.

Please initialize the log4j system properly warning

If you are encountering the error/warning when you're running a program that uses log4j, the solution is to add a log4j.properties that can be seen by the class loader. Normally it's in the "src" folder of your Java project: Add the following contents to the file

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

Open URL in new window with JavaScript

Use window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>

This will create a link titled Share Page which opens the current url in a new window with a height of 570 and width of 520.

RecyclerView - How to smooth scroll to top of item on a certain position?

Thanks, @droidev for the solution. If anyone looking for Kotlin solution, refer this:

    class LinearLayoutManagerWithSmoothScroller: LinearLayoutManager {
    constructor(context: Context) : this(context, VERTICAL,false)
    constructor(context: Context, orientation: Int, reverseValue: Boolean) : super(context, orientation, reverseValue)

    override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
        super.smoothScrollToPosition(recyclerView, state, position)
        val smoothScroller = TopSnappedSmoothScroller(recyclerView?.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private class TopSnappedSmoothScroller(context: Context?) : LinearSmoothScroller(context){
        var mContext = context
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
            return LinearLayoutManagerWithSmoothScroller(mContext as Context)
                    .computeScrollVectorForPosition(targetPosition)
        }

        override fun getVerticalSnapPreference(): Int {
            return SNAP_TO_START
        }


    }

}

Signing a Windows EXE file

You can get a free cheap code signing certificate from Certum if you're doing open source development.

I've been using their certificate for over a year, and it does get rid of the unknown publisher message from Windows.

As far as signing code I use signtool.exe from a script like this:

signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f "MyCert.pfx" /p MyPassword /d SignedFile.exe SignedFile.exe

vertical-align: middle doesn't work

You should set a fixed value to your span's line-height property:

.float, .twoline {
    line-height: 100px;
}

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:

//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

What is an optional value in Swift?

Let's take the example of an NSError, if there isn't an error being returned you'd want to make it optional to return Nil. There's no point in assigning a value to it if there isn't an error..

var error: NSError? = nil

This also allows you to have a default value. So you can set a method a default value if the function isn't passed anything

func doesntEnterNumber(x: Int? = 5) -> Bool {
    if (x == 5){
        return true
    } else {
        return false
    }
}

How to get TimeZone from android mobile?

According to http://developer.android.com/reference/android/text/format/Time.html you should be using Time.getCurrentTimezone() to retrieve the current timezone of the device.

How to send email attachments?

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import mimetypes
import email.mime.application

smtp_ssl_host = 'smtp.gmail.com'  # smtp.mail.yahoo.com
smtp_ssl_port = 465
s = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)
s.login(email_user, email_pass)


msg = MIMEMultipart()
msg['Subject'] = 'I have a picture'
msg['From'] = email_user
msg['To'] = email_user

txt = MIMEText('I just bought a new camera.')
msg.attach(txt)

filename = 'introduction-to-algorithms-3rd-edition-sep-2010.pdf' #path to file
fo=open(filename,'rb')
attach = email.mime.application.MIMEApplication(fo.read(),_subtype="pdf")
fo.close()
attach.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(attach)
s.send_message(msg)
s.quit()

For explanation, you can use this link it explains properly https://medium.com/@sdoshi579/to-send-an-email-along-with-attachment-using-smtp-7852e77623

How to "properly" create a custom object in JavaScript?

var Person = function (lastname, age, job){
this.name = name;
this.age = age;
this.job = job;
this.changeName = function(name){
this.lastname = name;
}
}
var myWorker = new Person('Adeola', 23, 'Web Developer');
myWorker.changeName('Timmy');

console.log("New Worker" + myWorker.lastname);

How to remove decimal values from a value of type 'double' in Java

Use Math.Round(double);

I have used it myself. It actually rounds off the decimal places.

d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20 

d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19 

Hope it Helps :-)

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

Selenium Webdriver move mouse to Point

IMHO you should pay your attention to Robot.class

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class

  Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
  Robot robot = new Robot();
  robot.mouseMove(coordinates.getX(),coordinates.getY()+120);

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked. In all browsers these are in event.screenX and event.screenY.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want. In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

More details you can get here

Hope this be helpful to you.

How do I make a Windows batch script completely silent?

Copies a directory named html & all its contents to a destination directory in silent mode. If the destination directory is not present it will still create it.

@echo off
TITLE Copy Folder with Contents

set SOURCE=C:\labs
set DESTINATION=C:\Users\MyUser\Desktop\html

xcopy %SOURCE%\html\* %DESTINATION%\* /s /e /i /Y >NUL

  1. /S Copies directories and subdirectories except empty ones.

  2. /E Copies directories and subdirectories, including empty ones. Same as /S /E. May be used to modify /T.

  3. /I If destination does not exist and copying more than one file, assumes that destination must be a directory.

  4. /Y Suppresses prompting to confirm you want to overwrite an existing destination file.

Force flushing of output to a file while bash script is still running

well like it or not this is how redirection works.

In your case the output (meaning your script has finished) of your script redirected to that file.

What you want to do is add those redirections in your script.

JavaFX - create custom button with image

A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.

import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class ImageButton extends Button {

    public void updateImages(final Image selected, final Image unselected) {
        final ImageView iv = new ImageView(selected);
        this.getChildren().add(iv);

        iv.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(unselected);
            }
        });
        iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(selected);
            }
        });

        super.setGraphic(iv);
    }
}

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

Foreign key and check constraints have the concept of being trusted or untrusted, as well as being enabled and disabled. See the MSDN page for ALTER TABLE for full details.

WITH CHECK is the default for adding new foreign key and check constraints, WITH NOCHECK is the default for re-enabling disabled foreign key and check constraints. It's important to be aware of the difference.

Having said that, any apparently redundant statements generated by utilities are simply there for safety and/or ease of coding. Don't worry about them.

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

You could try to reinstall the ca-certificates package, or explicitly allow the certificate in question as described here.

How can I use a C++ library from node.js?

Try shelljs to call c/c++ program or shared libraries by using node program from linux/unix . node-cmd an option in windows. Both packages basically enable us to call c/c++ program similar to the way we call from terminal/command line.

Eg in ubuntu:

const shell = require('shelljs');

shell.exec("command or script name");

In windows:

const cmd = require('node-cmd');
cmd.run('command here');

Note: shelljs and node-cmd are for running os commands, not specific to c/c++.

Template not provided using create-react-app

Try running your terminal as an administrator. I was having the same issue and nothing helped apart from opening the terminal as administrator and then doing the npx create-react-app yourAppName

Best way to alphanumeric check in JavaScript

Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal

_x000D_
_x000D_
function isAlphaNumeric ( str ) {

  /* Iterating character by character to get ASCII code for each character */
  for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {

    /* Collecting charCode from i index value in a string */
    code = str.charCodeAt( i ); 

    /* Validating charCode falls into anyone category */
    if (
        ( code > 47 && code < 58) // numeric (0-9)
        || ( code > 64 && code < 91) // upper alpha (A-Z)
        || ( code > 96 && code < 123 ) // lower alpha (a-z)
    ) {
      continue;
    } 

    /* If nothing satisfies then returning false */
    return false
  }

  /* After validating all the characters and we returning success message*/
  return true;
};

console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
_x000D_
_x000D_
_x000D_

Android Studio - Failed to apply plugin [id 'com.android.application']

Delete gradle cache files. It can be in path like C:\Users\username\.gradle\caches for Windows users. For UNIX based operating systems it will be ~/.gradle/caches.

Error with multiple definitions of function

Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.

C++ splits the load of generating machine executable code in following different phases -

  1. Preprocessing - This is where any macros - #defines etc you might be using get expanded.

  2. Compiling - Each cpp file along with all the #included files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.

    This is where C++ also checks that all functions defined (i.e. containing a body in { } e.g. void Foo( int x){ return Boo(x); }) are referring to other functions in a valid manner.

    The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int); ) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.

    Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).

  3. Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.

The latter is what is happening in your case. By doing a #include of the fun.cpp file, both fun.cpp and mainfile.cpp have a definition of funct() and the linker doesn't know which one to use in your program and is complaining about it.

The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct() in mainfile.cpp and instead move the declaration of funct() in a separate header file and include that in mainline.cpp. This way the compiler will get the declaration of funct() to work with and the linker would get just one definition of funct() from fun.cpp and will use it with confidence.

Format the date using Ruby on Rails

Since the timestamps are seconds since the UNIX epoch, you can use DateTime.strptime ("string parse time") with the correct specifier:

Date.strptime('1100897479', '%s')
#=> #<Date: 2004-11-19 ((2453329j,0s,0n),+0s,2299161j)>
Date.strptime('1100897479', '%s').to_s
#=> "2004-11-19"
DateTime.strptime('1100897479', '%s')
#=> #<DateTime: 2004-11-19T20:51:19+00:00 ((2453329j,75079s,0n),+0s,2299161j)>
DateTime.strptime('1100897479', '%s').to_s
#=> "2004-11-19T20:51:19+00:00"

Note that you have to require 'date' for that to work, then you can call it either as Date.strptime (if you only care about the date) or DateTime.strptime (if you want date and time). If you need different formatting, you can call DateTime#strftime (look at strftime.net if you have a hard time with the format strings) on it or use one of the built-in methods like rfc822.

How to update PATH variable permanently from Windows command line?

You can use:

setx PATH "%PATH%;C:\\Something\\bin"

However, setx will truncate the stored string to 1024 bytes, potentially corrupting the PATH.

/M will change the PATH in HKEY_LOCAL_MACHINE instead of HKEY_CURRENT_USER. In other words, a system variable, instead of the user's. For example:

SETX /M PATH "%PATH%;C:\your path with spaces"

You have to keep in mind, the new PATH is not visible in your current cmd.exe.

But if you look in the registry or on a new cmd.exe with "set p" you can see the new value.

How do I localize the jQuery UI Datepicker?

1. You need to load the jQuery UI i18n files:

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/i18n/jquery-ui-i18n.min.js">
</script>

2. Use $.datepicker.setDefaults function to set defaults for ALL datepickers.

3. In case you want to override setting(s) before setting defaults you can use this:

var options = $.extend(
    {},                                  // empty object
    $.datepicker.regional["fr"],         // fr regional
    { dateFormat: "d MM, y" /*, ... */ } // your custom options
);
$.datepicker.setDefaults(options);

The order of parameters is important because of the way jQuery.extend works. Two incorrect examples:

/*
 * This overwrites the global variable itself instead of creating a
 * customized copy of french regional settings
 */
$.extend($.datepicker.regional["fr"], { dateFormat: "d MM, y"});

/*
 * The desired dateFormat is overwritten by french regional 
 * settings' date format
 */
$.extend({ dateFormat: "d MM, y"}, $.datepicker.regional["fr"]);

What can cause a “Resource temporarily unavailable” on sock send() command

That's because you're using a non-blocking socket and the output buffer is full.

From the send() man page

   When the message does not fit into  the  send  buffer  of  the  socket,
   send() normally blocks, unless the socket has been placed in non-block-
   ing I/O mode.  In non-blocking mode it  would  return  EAGAIN  in  this
   case.  

EAGAIN is the error code tied to "Resource temporarily unavailable"

Consider using select() to get a better control of this behaviours

How to convert currentTimeMillis to a date in Java?

tl;dr

Instant.ofEpochMilli( 1_322_018_752_992L )     // Parse count of milliseconds-since-start-of-1970-UTC into an `Instant`.
       .atZone( ZoneId.of( "Africa/Tunis" ) )  // Assign a time zone to the `Instant` to produce a `ZonedDateTime` object.

Details

The other answers use outmoded or incorrect classes.

Avoid the old date-time classes such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome.

java.time

The java.time framework comes built into Java 8 and later. Much of the functionality is backported to Java 6 & 7 and further adapted to Android. Made by the some of the same folks as had made Joda-Time.

An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is first moment of 1970 in UTC.

Assuming your input data is a count of milliseconds from 1970-01-01T00:00:00Z (not clear in the Question), then we can easily instantiate an Instant.

Instant instant = Instant.ofEpochMilli( 1_322_018_752_992L );

instant.toString(): 2011-11-23T03:25:52.992Z

The Z in that standard ISO 8601 formatted string is short for Zulu and means UTC.

Apply a time zone using a proper time zone name, to get a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( zoneId );

See this code run live at IdeOne.com.

Asia/Kolkata time zone ?

I am guessing your are had an India time zone affecting your code. We see here that adjusting into Asia/Kolkata time zone renders the same time-of-day as you report, 08:55 which is five and a half hours ahead of our UTC value 03:25.

2011-11-23T08:55:52.992+05:30[Asia/Kolkata]

Default zone

You can apply the current default time zone of the JVM. Beware that the default can change at any moment during runtime. Any code in any thread of any app within the JVM can change the current default. If important, ask the user for their desired/expected time zone.

ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

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

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

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

how to implement a long click listener on a listview

or try this code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
}); 

How to create duplicate table with new name in SQL Server 2008

I have used this query it is created new table with existing data.

Query : select * into [newtablename] from [existingtable]

Here is the link Microsoft instructions. https://docs.microsoft.com/en-us/sql/relational-databases/tables/duplicate-tables?view=sql-server-2017

Simple http post example in Objective-C?

Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

How to concatenate strings in django templates?

From the docs:

This tag can be used in two ways:

  • {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend.
  • {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

So seems like you can't use a filter to manipulate the argument. In the calling view you have to either instantiate the ancestor template or create an string variable with the correct path and pass it with the context.

How to get current local date and time in Kotlin

To get the current Date in Kotlin do this:

val dateNow = Calendar.getInstance().time

Convert string with commas to array

Another option using the ES6 is using Spread syntax.

var convertedArray = [..."01234"];

_x000D_
_x000D_
var stringToConvert = "012";_x000D_
var convertedArray  = [...stringToConvert];_x000D_
console.log(convertedArray);
_x000D_
_x000D_
_x000D_

curl error 18 - transfer closed with outstanding read data remaining

I got this error when i was accidentally downloading a file onto itself.
(I had created a symlink in an sshfs mount of the remote directory to make it available for download, forgot to switch the working directory, and used -OJ).

I guess it won’t really »help« you when you read this, since it means your file got trashed.

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

How to multi-line "Replace in files..." in Notepad++

The workaround is

  1. search and replace \r\n to thisismynewlineword

(this will remove all the new lines and there should be whole one line)

  1. now perform your replacements

  2. search and replace thisismynewlineword to \r\n

(to undo the step 1)

std::wstring VS std::string

So, every reader here now should have a clear understanding about the facts, the situation. If not, then you must read paercebal's outstandingly comprehensive answer [btw: thanks!].

My pragmatical conclusion is shockingly simple: all that C++ (and STL) "character encoding" stuff is substantially broken and useless. Blame it on Microsoft or not, that will not help anyway.

My solution, after in-depth investigation, much frustration and the consequential experiences is the following:

  1. accept, that you have to be responsible on your own for the encoding and conversion stuff (and you will see that much of it is rather trivial)

  2. use std::string for any UTF-8 encoded strings (just a typedef std::string UTF8String)

  3. accept that such an UTF8String object is just a dumb, but cheap container. Do never ever access and/or manipulate characters in it directly (no search, replace, and so on). You could, but you really just really, really do not want to waste your time writing text manipulation algorithms for multi-byte strings! Even if other people already did such stupid things, don't do that! Let it be! (Well, there are scenarios where it makes sense... just use the ICU library for those).

  4. use std::wstring for UCS-2 encoded strings (typedef std::wstring UCS2String) - this is a compromise, and a concession to the mess that the WIN32 API introduced). UCS-2 is sufficient for most of us (more on that later...).

  5. use UCS2String instances whenever a character-by-character access is required (read, manipulate, and so on). Any character-based processing should be done in a NON-multibyte-representation. It is simple, fast, easy.

  6. add two utility functions to convert back & forth between UTF-8 and UCS-2:

    UCS2String ConvertToUCS2( const UTF8String &str );
    UTF8String ConvertToUTF8( const UCS2String &str );
    

The conversions are straightforward, google should help here ...

That's it. Use UTF8String wherever memory is precious and for all UTF-8 I/O. Use UCS2String wherever the string must be parsed and/or manipulated. You can convert between those two representations any time.

Alternatives & Improvements

  • conversions from & to single-byte character encodings (e.g. ISO-8859-1) can be realized with help of plain translation tables, e.g. const wchar_t tt_iso88951[256] = {0,1,2,...}; and appropriate code for conversion to & from UCS2.

  • if UCS-2 is not sufficient, than switch to UCS-4 (typedef std::basic_string<uint32_t> UCS2String)

ICU or other unicode libraries?

For advanced stuff.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

The WebDriver have to wait until the Element is located and a timeout is after 10 seconds.

WebElement myDynamicElement1 = new WebDriverWait(driver, 10).until(
    ExpectedConditions.presenceOfElementLocated(
        By.name("createForm:dateInput_input")
    )
);

Pyinstaller setting icons don't change

The below command can set the icon on an executable file.

Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py

For example:

If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

Then the command should be as below. The final executable file will be generated inside the dist folder

pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py

Check if a class is derived from a generic class

Here's a little method I created for checking that a object is derived from a specific type. Works great for me!

internal static bool IsDerivativeOf(this Type t, Type typeToCompare)
{
    if (t == null) throw new NullReferenceException();
    if (t.BaseType == null) return false;

    if (t.BaseType == typeToCompare) return true;
    else return t.BaseType.IsDerivativeOf(typeToCompare);
}

Make HTML5 video poster be same size as video itself

<video src="videofile.webm" poster="posterimage.jpg" controls preload="metadata">
    Sorry, your browser doesn't support embedded videos.
</video>

Cover

video{
   object-fit: cover; /*to cover all the box*/
}

Fill

video{
   object-fit: fill; /*to add black content at top and bottom*/
   object-position: 0 -14px; /* to center our image*/
}

Note that the video controls are over our image, so our image is not completly showed. If you are using object-fit cover, edit your image on a visual app as photoshop and add a margin bottom content.

how to Call super constructor in Lombok

Lombok does not support that also indicated by making any @Value annotated class final (as you know by using @NonFinal).

The only workaround I found is to declare all members final yourself and use the @Data annotation instead. Those subclasses need to be annotated by @EqualsAndHashCode and need an explicit all args constructor as Lombok doesn't know how to create one using the all args one of the super class:

@Data
public class A {
    private final int x;
    private final int y;
}

@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
    private final int z;

    public B(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }
}

Especially the constructors of the subclasses make the solution a little untidy for superclasses with many members, sorry.

Extract a single (unsigned) integer from a string

This script creates a file at first , write numbers to a line and changes to a next line if gets a character other than number. At last, again it sorts out the numbers to a list.

string1 = "hello my name 12 is after 198765436281094and14 and 124de"
f= open("created_file.txt","w+")
for a in string1:
    if a in ['1','2','3','4','5','6','7','8','9','0']:
        f.write(a)
    else:
        f.write("\n" +a+ "\n")
f.close()


#desired_numbers=[x for x in open("created_file.txt")]

#print(desired_numbers)

k=open("created_file.txt","r")
desired_numbers=[]
for x in k:
    l=x.rstrip()
    print(len(l))
    if len(l)==15:
        desired_numbers.append(l)


#desired_numbers=[x for x in k if len(x)==16]
print(desired_numbers)

JQuery datepicker language

Maybe you don't have a language file:

Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n

A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:

http://api.jqueryui.com/datepicker/

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

Is your MySQL server version 5.5.3 or greater?

The utf8mb4, utf16, and utf32 character sets were added in MySQL 5.5.3.

http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-sets.html

How does BitLocker affect performance?

My current work machine came with bitlocker, and being an upgrade from the prior model. It only seemed faster to me. What I have found, however, is that bitlocker is more bullet proof than truecrypt, when it comes to accurately laying down the data. I do a lot of work in SAS which constantly writes backup copies to disk as it moves along and shoots a variety of output types to disk at the end. SAS works fine writing output from multithreaded processes back to bitlocker and doesn't seem to know it's there. This has not been the case for me with truecrypt. I'm not sure what happens or how, but I found that processes got out of synch when working with source/output data in a truecrypt container, which is what I installed on my second work computer since it had no bitlocker. The constant backups were shooting to an SSD while the truecrypt results were on a regular HD. Maybe that speed difference helped trip it up. Whatever the cause, I had to quit using truecrypt on that second computer because it made my SAS results out of synch with respect to processing order and it screwed up some of my processes and data. Scary stuff in my world.

I work with people who have successfully used Truecrypt on the exact same computer, but they weren't using a disk intensive app. like SAS.

Bitlocker to Go, the encryption which bitlocker applies to thumb-drives, does slow things down quite a bit when it comes to read/write times. It's not too hard to use as long as you remember your password on the thumbdrive, and are willing to wait for it to format/initialize the drive, but in my experience it made access to the flash drive about 4 times as slow. Don't know why it would slow down a thumb drive and not a disk but that's how it was for me and my coworker.

Based on my success with bitlocker at work, I bought Windows Pro for my home computer to get bitlocker and plan to encrypt some directories with it for things like financials.

Default keystore file does not exist?

For Mac/Linux debug keystore, the Android docs have:

keytool -exportcert -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

But there is something that may not be obvious: If you put the backslash, make sure to do a shift + return in terminal after the backslash so that the second that starts with -alias is on a new line. Simply pasting as-is will not work.

Your terminal (if successful) will look something like this:

$ keytool -exportcert -list -v \
? -alias androiddebugkey -keystore ~/.android/debug.keystore
Enter keystore password: 

The default debug password is: android

Side note: In Android Studio you can manage signing in:

File > Project Structure > Modules - (Your App) > Signing

Find row in datatable with specific id

try this code

DataRow foundRow = FinalDt.Rows.Find(Value);

but set at lease one primary key

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

Fastest way to list all primes below N

Using Sundaram's Sieve, I think I broke pure-Python's record:

def sundaram3(max_n):
    numbers = range(3, max_n+1, 2)
    half = (max_n)//2
    initial = 4

    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)

        if initial > half:
            return [2] + filter(None, numbers)

Comparasion:

C:\USERS>python -m timeit -n10 -s "import get_primes" "get_primes.get_primes_erat(1000000)"
10 loops, best of 3: 710 msec per loop

C:\USERS>python -m timeit -n10 -s "import get_primes" "get_primes.daniel_sieve_2(1000000)"
10 loops, best of 3: 435 msec per loop

C:\USERS>python -m timeit -n10 -s "import get_primes" "get_primes.sundaram3(1000000)"
10 loops, best of 3: 327 msec per loop

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

Datatables Select All Checkbox

The solution given by @annoyingmouse works for me.

But to use the checkbox in the header cell, I also had to fix select.dataTables.css.
It seems that they used :

table.dataTable tbody th.select-checkbox

instead of :

table.dataTable thead th.select-checkbox

So I had to add this to my css :

table.dataTable thead th.select-checkbox {
  position: relative;
}
table.dataTable thead th.select-checkbox:before,
table.dataTable thead th.select-checkbox:after {
  display: block;
  position: absolute;
  top: 1.2em;
  left: 50%;
  width: 12px;
  height: 12px;
  box-sizing: border-box;
}
table.dataTable tbody td.select-checkbox:before,
table.dataTable thead th.select-checkbox:before {
  content: ' ';
  margin-top: -6px;
  margin-left: -6px;
  border: 1px solid black;
  border-radius: 3px;
}

How can I strip first X characters from string using sed?

pipe it through awk '{print substr($0,42)}' where 42 is one more than the number of characters to drop. For example:

$ echo abcde| awk '{print substr($0,2)}'
bcde
$

How to declare a global variable in C++

Declare extern int x; in file.h. And define int x; only in one cpp file.cpp.

Cannot make a static reference to the non-static method fxn(int) from the type Two

  1. A static method can NOT access a Non-static method or variable.

  2. public static void main(String[] args) is a static method, so can NOT access the Non-static public static int fxn(int y) method.

  3. Try it this way...

    static int fxn(int y)

    public class Two {
    
    
        public static void main(String[] args) {
            int x = 0;
    
            System.out.println("x = " + x);
            x = fxn(x);
            System.out.println("x = " + x);
        }
    
        static int fxn(int y) {
            y = 5;
            return y;
        }
    

    }

Parsing a JSON string in Ruby

It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:

JSON.parse(string)

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

In my case my site on IIS was pointing to a different project than the one I was running on visual studio.

Java: How to convert String[] to List or Set

Arrays.asList() would do the trick here.

String[] words = {"ace", "boom", "crew", "dog", "eon"};   

List<String> wordList = Arrays.asList(words);  

For converting to Set, you can do as below

Set<T> mySet = new HashSet<T>(Arrays.asList(words)); 

How to programmatically send SMS on the iPhone?

You can use a sms:[target phone number] URL to open the SMS application, but there are no indications on how to prefill a SMS body with text.

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

How to move columns in a MySQL table?

phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.

Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.

my phpMyAdmin version is 4.1.7

Communicating between a fragment and an activity - best practices

You can create declare a public interface with a function declaration in the fragment and implement the interface in the activity. Then you can call the function from the fragment.

how to stop a running script in Matlab

One solution I adopted--for use with java code, but the concept is the same with mexFunctions, just messier--is to return a FutureValue and then loop while FutureValue.finished() or whatever returns true. The actual code executes in another thread/process. Wrapping a try,catch around that and a FutureValue.cancel() in the catch block works for me.

In the case of mex functions, you will need to return somesort of pointer (as an int) that points to a struct/object that has all the data you need (native thread handler, bool for complete etc). In the case of a built in mexFunction, your mexFunction will most likely need to call that mexFunction in the separate thread. Mex functions are just DLLs/shared objects after all.

PseudoCode

FV = mexLongProcessInAnotherThread();
try
  while ~mexIsDone(FV);
    java.lang.Thread.sleep(100); %pause has a memory leak
    drawnow; %allow stdout/err from mex to display in command window
  end
catch
  mexCancel(FV);
end

"The operation is not valid for the state of the transaction" error and transaction scope

When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.

When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:

<system.transactions> 
        <machineSettings maxTimeout="00:05:00" /> 
</system.transactions>

How to crop an image using C#?

Check out this link: http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
}

Find and Replace string in all files recursive using grep and sed

sed expression needs to be quoted

sed -i "s/$oldstring/$newstring/g"

How to know Laravel version and where is it defined?

run php artisan --version from your console.

The version string is defined here:

https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Application.php

/**
 * The Laravel framework version.
 *
 * @var string
 */
 const VERSION = '5.5-dev';

Remove char at specific index - python

rem = lambda x, unwanted : ''.join([ c for i, c in enumerate(x) if i != unwanted])
rem('1230004', 4)
'123004'

How to define a circle shape in an Android XML drawable file?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/text_color_green"/>
            <!-- Set the same value for both width and height to get a circular shape -->
            <size android:width="250dp" android:height="250dp"/>
        </shape>
    </item>
</selector>

Get string character by index - Java

CharAt function not working

Edittext.setText(YourString.toCharArray(),0,1);

This code working fine

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

In case you are using NodeJS/Express as back-end and ReactJS/axios as front-end within a development environment in MacOS, you need to run both sides under https. Below is what it finally worked for me (after many hours of deep dive & testing):

Step 1: Create an SSL certificate

Just follow the steps from How to get HTTPS working on your local development environment in 5 minutes

You will end up with a couple of files to be used as credentials to run the https server and ReactJS web:

server.key & server.crt

You need to copy them in the root folders of both the front and back ends (in a Production environment, you might consider copying them in ./ssh for the back-end).

Step 2: Back-end setup

I read a lot of answers proposing the use of 'cors' package or even setting ('Access-Control-Allow-Origin', '*'), which is like saying: "Hackers are welcome to my website". Just do like this:

import express from 'express';
const emailRouter = require('./routes/email');  // in my case, I was sending an email through a form in ReactJS
const fs = require('fs');
const https = require('https');

const app = express();
const port = 8000;

// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "https://localhost:3000");
    next();
});

// Routes definition
app.use('/email', emailRouter);

// HTTPS server
const credentials = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
};

const httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, () => {
    console.log(`Back-end running on port ${port}`);
});

In case you want to test if the https is OK, you can replace the httpsServer constant by the one below:

https.createServer(credentials, (req: any, res: any) => {
  res.writeHead(200);
  res.end("hello world from SSL\n");
}).listen(port, () => {
  console.log(`HTTPS server listening on port ${port}...`);
});

And then access it from a web browser: https://localhost:8000/

Step 3: Front-end setup

This is the axios request from the ReactJS front-end:

    await axios.get(`https://localhost:8000/email/send`, {
        params: {/* whatever data you want to send */ },
        headers: {
            'Content-Type': 'application/json',
        }
    })

And now, you need to launch your ReactJS web in https mode using the credentials for SSL we already created. Type this in your MacOS terminal:

HTTPS=true SSL_CRT_FILE=server.crt SSL_KEY_FILE=server.key npm start

At this point, you are sending a request from an https connection at port 3000 from your front-end, to be received by an https connection at port 8000 by your back-end. CORS should be happy with this ;)

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

Convert an image to grayscale

Bitmap d = new Bitmap(c.Width, c.Height);

for (int i = 0; i < c.Width; i++)
{
    for (int x = 0; x < c.Height; x++)
    {
        Color oc = c.GetPixel(i, x);
        int grayScale = (int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11));
        Color nc = Color.FromArgb(oc.A, grayScale, grayScale, grayScale);
        d.SetPixel(i, x, nc);
    }
}

This way it also keeps the alpha channel.
Enjoy.

Get only records created today in laravel

Use Mysql default CURDATE function to get all the records of the day.

    $records = DB::table('users')->select(DB::raw('*'))
                  ->whereRaw('Date(created_at) = CURDATE()')->get();
    dd($record);

Note

The difference between Carbon::now vs Carbon::today is just time.

e.g

Date printed through Carbon::now will look like something:

2018-06-26 07:39:10.804786 UTC (+00:00)

While with Carbon::today:

2018-06-26 00:00:00.0 UTC (+00:00)

To get the only records created today with now can be fetched as:

Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();

while with today:

Post::whereDate('created_at', Carbon::today())->get();

UPDATE

As of laravel 5.3, We have default where clause whereDate / whereMonth / whereDay / whereYear

$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();

OR with DB facade

$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();

Usage of the above listed where clauses

$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"

Query Builder Docs

Copy rows from one Datatable to another DataTable?

below sample would be the fastest way to copy one row. each cell is being copied based on the column name. in case you dont need a specific cell to copy then have a try catch or add if. if your going to copy more than 1 row then loop the code below.

DataRow dr = dataset1.Tables[0].NewRow();
for (int i = 0; i < dataset1.Tables[1].Columns.Count; i++)
{
    dr[dataset1.Tables[1].Columns[i].ColumnName] = dataset1.Tables[1].Rows[0][i];
}

datasetReport.Tables[0].Rows.Add(dr);

dataset1.Tables[1].Rows[0][i]; change the index 0 to your specified row index or you can use a variable if your going to loop or if its going to be logical

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

Send email using the GMail SMTP server from a PHP page

SwiftMailer can send E-Mail using external servers.

here is an example that shows how to use a Gmail server:

require_once "lib/Swift.php";
require_once "lib/Swift/Connection/SMTP.php";

//Connect to localhost on port 25
$swift =& new Swift(new Swift_Connection_SMTP("localhost"));


//Connect to an IP address on a non-standard port
$swift =& new Swift(new Swift_Connection_SMTP("217.147.94.117", 419));


//Connect to Gmail (PHP5)
$swift = new Swift(new Swift_Connection_SMTP(
    "smtp.gmail.com", Swift_Connection_SMTP::PORT_SECURE, Swift_Connection_SMTP::ENC_TLS));

What is the use of rt.jar file in java?

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

How to set python variables to true or false?

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

Passing arguments forward to another javascript function

Use .apply() to have the same access to arguments in function b, like this:

function a(){
    b.apply(null, arguments);
}
function b(){
   alert(arguments); //arguments[0] = 1, etc
}
a(1,2,3);?

You can test it out here.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

Added @TABLE(name = "TABLE_NAME") annotation and fixed. Check your annotations and hibernate.cfg.xml file. This is the sample entity file that works:

import javax.persistence.*;

@Entity
@Table(name = "VENDOR")
public class Vendor {

    //~ --- [INSTANCE FIELDS] ------------------------------------------------------------------------------------------
    private int    id;
    private String name;

    //~ --- [METHODS] --------------------------------------------------------------------------------------------------
    @Override
    public boolean equals(final Object o) {    
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Vendor vendor = (Vendor) o;

        if (id != vendor.id) {
            return false;
        }

        if (name != null ? !name.equals(vendor.name) : vendor.name != null) {
            return false;
        }

        return true;
    }

    //~ ----------------------------------------------------------------------------------------------------------------
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    public int getId() {
        return id;
    }

    @Basic
    @Column(name = "NAME")
    public String getName() {

        return name;
    }

    public void setId(final int id) {
        this.id = id;
    }

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

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}

MongoDB query with an 'or' condition

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

Use "in" or "where".

Its gonna be something like this:

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

Installing Python packages from local file system folder to virtualenv with pip

I am installing pyfuzzybut is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy.

I tried the accepted answer

pip install  --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy

But it does not work either and returns the following error:

Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy

At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html

Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip

So the following command worked for me:

pip install ../pyfuzzy-0.1.0.tar.gz.

Hope it can help you.

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

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

Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:

FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
    f2.Demand();
}
catch (SecurityException s)
{
    Console.WriteLine(s.Message);
}

Understanding .NET Code Access Security

Is “Code Access Security” of any real world use?

Determine if variable is defined in Python

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

Why doesn't C++ have a garbage collector?

One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:

  • deterministic lifetimes of objects (reference counting gives you this, but GC doesn't. Although it may not be that big of a deal).
  • what happens if a destructor throws when the object is being garbage collected? Most languages ignore this exception, since theres really no catch block to be able to transport it to, but this is probably not an acceptable solution for C++.
  • How to enable/disable it? Naturally it'd probably be a compile time decision but code that is written for GC vs code that is written for NOT GC is going to be very different and probably incompatible. How do you reconcile this?

These are just a few of the problems faced.

I keep getting "Uncaught SyntaxError: Unexpected token o"

SyntaxError: Unexpected token o in JSON

This also happens when you forget to use the await keyword for a method that returns JSON data.

For example:

async function returnJSONData()
{
   return "{\"prop\": 2}";
}

var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);

will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.

To fix just add await as you're supposed to:

var json_str = await returnJSONData();

This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.

How to run Maven from another directory (without cd to project dir)?

For me, works this way: mvn -f /path/to/pom.xml [goals]

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

e.g.

var d = "";
var json = JSON.parse(d);

or if you are using AngularJS

var d = "";
var json = angular.fromJson(d);

In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.

Java: Find .txt files in specified folder

It's really useful, I used it with a slight change:

filename=directory.list(new FilenameFilter() { 
    public boolean accept(File dir, String filename) { 
        return filename.startsWith(ipro); 
    }
});

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Here is the solution for Ubuntu users

First we have to stop postgresql

sudo /etc/init.d/postgresql stop

Create a new file called /etc/apt/sources.list.d/pgdg.list and add below line

deb http://apt.postgresql.org/pub/repos/apt/ utopic-pgdg main

Follow below commands

wget -q -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get install postgresql-9.4
sudo pg_dropcluster --stop 9.4 main 
sudo /etc/init.d/postgresql start

Now we have everything, just need to upgrade it as below

sudo pg_upgradecluster 9.3 main
sudo pg_dropcluster 9.3 main

That's it. Mostly upgraded cluster will run on port number 5433. Check it with below command

sudo pg_lsclusters

Can't change table design in SQL Server 2008

You can directly add a constraint for table

ALTER TABLE TableName
ADD CONSTRAINT ConstraintName PRIMARY KEY(ColumnName)
GO 

Make sure your primary key column should not have any null values.

Option 2:

you can change your SQL Management Studio Options like

To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.

Where is the Docker daemon log?

I was not able to find the logs under Manjaro 20/Arch Linux. Instead i just stopped the docker daemon process and restarted daemon in debug mode with $ sudo dockerd -D to produce logs. It's unfortunate that the official Docker docs don't provide this info for Arch.
This should not only work for Arch, but for other systems in general.

Activity transition in Android

Yes. You can tell the OS what kind of transition you want to have for your activity.

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getWindow().setWindowAnimations(ANIMATION);

    ...

}

Where ANIMATION is an integer referring to a built in animation in the OS.

How can you use optional parameters in C#?

From this site:

http://www.tek-tips.com/viewthread.cfm?qid=1500861&page=1

C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:

using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}

In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.

Android Studio error: "Environment variable does not point to a valid JVM installation"

Do step by step as shown in this YouTube Video

Go to: System -> Advanced system settings -> Environment Variables

Add a new variable to you profile NAME=JAVA_HOME STRING: Program Files/java/"your string" Save and Start Android Studio ;)

enter image description here

Start and stop a timer PHP

As alternative, php has a built-in timer controller: new EvTimer().

It can be used to make a task scheduler, with proper handling of special cases.

This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year, it will still time out after(roughly) one hour.

The callback is guaranteed to be invoked only after its timeout has passed (...). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values.

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

The first two parameters allows to controls the time delay before execution, and the number of iterations.

The third parameter is a callback function, called at each iteration.

after

    Configures the timer to trigger after after seconds.

repeat

    If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
    If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

https://www.php.net/manual/en/class.evtimer.php

https://www.php.net/manual/en/evtimer.construct.php

$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

We can of course easily create this with basic looping and some tempo with sleep(), usleep(), or hrtime(), but new EvTimer() allows cleans and organized multiples calls, while handling special cases like overlapping.

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

java.net.SocketException: Software caused connection abort: recv failed

This error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).

An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.

Don't use URL.open(), use Apache-Commons HttpClient which has a retry mechanism, connection pooling, keep-alive and many other features.

Sample usage:

HttpClient httpClient = HttpClients.custom()
            .setConnectionTimeToLive(20, TimeUnit.SECONDS)
            .setMaxConnTotal(400).setMaxConnPerRoute(400)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setSocketTimeout(30000).setConnectTimeout(5000).build())
            .setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))
            .build();
// the httpClient should be re-used because it is pooled and thread-safe.

HttpGet request = new HttpGet(uri);
HttpResponse response = httpClient.execute(request);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// handle response ...

A regular expression to exclude a word/string

simpler:

re.findall(r'/(?!ignoreme)(\w+)',  "/hello /ignoreme and /ignoreme2 /ignoreme2M.")

you will get:

['hello']

How to "log in" to a website using Python's Requests module?

I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:

Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.

Once you've got that, you can use a requests.Session() instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.

Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.

Example

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'inUserName': 'username',
    'inUserPass': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post('LOGIN_URL', data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    r = s.get('A protected web page url')
    print r.text
        # etc...

How to make HTML table cell editable?

HTML5 supports contenteditable,

<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>

3rd party edit

To quote the mdn entry on contenteditable

The attribute must take one of the following values:

  • true or the empty string, which indicates that the element must be editable;

  • false, which indicates that the element must not be editable.

If this attribute is not set, its default value is inherited from its parent element.

This attribute is an enumerated one and not a Boolean one. This means that the explicit usage of one of the values true, false or the empty string is mandatory and that a shorthand ... is not allowed.

// wrong not allowed
<label contenteditable>Example Label</label> 

// correct usage
<label contenteditable="true">Example Label</label>.

Failed to install Python Cryptography package with PIP and setup.py

I encountered a similar issue recently. In my case the versions of cffi and cryptography written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi with the last available version.

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

You need to add two jars into the WEB-INF/lib directory or your webapp (or lib directory of the server):

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

You can't directly get an iterator for an array.

But you can use a List, backed by your array, and get an ierator on this list. For that, your array must be an Integer array (instead of an int array):

Integer[] arr={1,2,3};
List<Integer> arrAsList = Arrays.asList(arr);
Iterator<Integer> iter = arrAsList.iterator();

Note: it is only theory. You can get an iterator like this, but I discourage you to do so. Performances are not good compared to a direct iteration on the array with the "extended for syntax".

Note 2: a list construct with this method doesn't support all methods (since the list is backed by the array which have a fixed size). For example, "remove" method of your iterator will result in an exception.

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

If you get a

sudo: add-apt-repository: command not found

then you need to run the following command

sudo apt-get install software-properties-common python-software-properties

How to get config parameters in Symfony2 Twig Templates

On newer versions of Symfony2 (using a parameters.yml instead of parameters.ini), you can store objects or arrays instead of key-value pairs, so you can manage your globals this way:

config.yml (edited only once):

# app/config/config.yml
twig:
  globals:
    project: %project%

parameters.yml:

# app/config/parameters.yml
project:
  name:       myproject.com
  version:    1.1.42

And then in a twig file, you can use {{ project.version }} or {{ project.name }}.

Note: I personally dislike adding things to app, just because that's the Symfony's variable and I don't know what will be stored there in the future.

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

How do I specify the platform for MSBuild?

There is an odd case I got in VS2017, about the space between ‘Any’ and 'CPU'. this is not about using command prompt.

If you have a build project file, which could call other solution files. You can try to add the space between Any and CPU, like this (the Platform property value):

<MSBuild Projects="@(SolutionToBuild2)" Properties ="Configuration=$(ProjectConfiguration);Platform=Any CPU;Rerun=$(MsBuildReRun);" />

Before I fix this build issue, it is like this (ProjectPlatform is a global variable, was set to 'AnyCPU'):

<MSBuild Projects="@(SolutionToBuild1)" Properties ="Configuration=$(ProjectConfiguration);Platform=$(ProjectPlatform);Rerun=$(MsBuildReRun);" />

Also, we have a lot projects being called using $ (ProjectPlatform), which is 'AnyCPU' and work fine. If we open proj file, we can see lines liket this and it make sense.

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">

So my conclusion is, 'AnyCPU' works for calling project files, but not for calling solution files, for calling solution files, using 'Any CPU' (add the space.)

For now, I am not sure if it is a bug of VS project file or MSBuild. I am using VS2017 with VS2017 build tools installed.

jQuery remove all list items from an unordered list

$("ul").empty() should work and clear the childrens. you can see it here:

http://jsfiddle.net/ZKFA5/

Accessing a property in a parent Component

There are different way:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
  • data-binding
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">

"std::endl" vs "\n"

I've always had a habit of just using std::endl because it is easy for me to see.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

Importing a long list of constants to a Python file

And ofcourse you can do:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT

How to split the name string in mysql?

You can use bewlo one also:

SELECT SUBSTRING_INDEX(Name, ' ', 1) AS fname,
SUBSTRING_INDEX(SUBSTRING_INDEX(Name,' ', 2), ' ',-1) AS mname,
SUBSTRING_INDEX(Name, ' ', -1) as lname FROM mytable;

CMD command to check connected USB devices

you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.

Call Javascript onchange event by programmatically changing textbox value

You can put it in a different class and then call a function. This works when ajax refresh

$(document).on("change", ".inputQty", function(e) {

//Call a function(input,input);
});

var self = this?

This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:

var abc = 1; // we want to use this variable in embedded functions

function xyz(){
  console.log(abc); // it is available here!
  function qwe(){
    console.log(abc); // it is available here too!
  }
  ...
};

This technique relies on using a closure. But it doesn't work with this because this is a pseudo variable that may change from scope to scope dynamically:

// we want to use "this" variable in embedded functions

function xyz(){
  // "this" is different here!
  console.log(this); // not what we wanted!
  function qwe(){
    // "this" is different here too!
    console.log(this); // not what we wanted!
  }
  ...
};

What can we do? Assign it to some variable and use it through the alias:

var abc = this; // we want to use this variable in embedded functions

function xyz(){
  // "this" is different here! --- but we don't care!
  console.log(abc); // now it is the right object!
  function qwe(){
    // "this" is different here too! --- but we don't care!
    console.log(abc); // it is the right object here too!
  }
  ...
};

this is not unique in this respect: arguments is the other pseudo variable that should be treated the same way — by aliasing.

jQuery: how do I animate a div rotation?

If you're designing for an iOS device or just webkit, you can do it with no JS whatsoever:

CSS:

@-webkit-keyframes spin {  
from {  
    -webkit-transform: rotate(0deg);  
}  
to {  
    -webkit-transform: rotate(360deg);  
    } 
}

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: linear;
    -webkit-animation-duration: 3s; 
}

This would trigger the animation on load. If you wanted to trigger it on hover, it might look like this:

.wheel {
    width:40px;
    height:40px;
    background:url(wheel.png);
}

.wheel:hover {
    -webkit-animation-name: spin; 
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-timing-function: ease-in-out;
    -webkit-animation-duration: 3s; 
}

How to convert upper case letters to lower case

str.lower() converts all cased characters to lowercase.

Handling a Menu Item Click Event - Android

Add Following Code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.new_item:
        Intent i = new Intent(this,SecondActivity.class);
            this.startActivity(i);
            return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

How to get DataGridView cell value in messagebox?

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
           int rowIndex = e.RowIndex; // Get the order of the current row 
            DataGridViewRow row = dataGridView1.Rows[rowIndex];//Store the value of the current row in a variable
            MessageBox.Show(row.Cells[rowIndex].Value.ToString());//show message for current row
    }

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

Access elements in json object like an array

I noticed a couple of syntax errors, but other than that, it should work fine:

var arr = [
  ["Blankaholm", "Gamleby"],
  ["2012-10-23", "2012-10-22"],
  ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har."], //<- syntax error here
  ["57.586174","16.521841"], ["57.893162","16.406090"]
];


console.log(arr[4]);    //["57.893162","16.406090"]
console.log(arr[4][0]); //57.893162

Permission denied on CopyFile in VBS

I've only ever seen CopyFile fail with a "permission denied" error in one of these 3 scenarios:

  • An actual permission problem with either source or destination.
  • Destination path is a folder, but does not have a trailing backslash.
  • Source file is locked by an application.

python list by value not by reference

To create a copy of a list do this:

b = a[:]

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

jQuery UI autocomplete with JSON

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

How to make blinking/flashing text with CSS 3

I don't know why but animating only the visibility property is not working on any browser.

What you can do is animate the opacity property in such a way that the browser doesn't have enough frames to fade in or out the text.

Example:

_x000D_
_x000D_
span {_x000D_
  opacity: 0;_x000D_
  animation: blinking 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinking {_x000D_
  from,_x000D_
  49.9% {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  50%,_x000D_
  to {_x000D_
    opacity: 1;_x000D_
  }_x000D_
}
_x000D_
<span>I'm blinking text</span>
_x000D_
_x000D_
_x000D_

Why is the minidlna database not being refreshed?

There is a patch for the sourcecode of minidlna at sourceforge available that does not make a full rescan, but a kind of incremental scan. That worked fine, but with some later version, the patch is broken. See here Link to SF

Regards Gerry

jQuery change method on input type="file"

I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange="" attribute to the input tag:

<input type='file' onchange='getFilename(this)'/>

function getFileName(elm) {
   var fn = $(elm).val();
   ....
}

EDIT:

function getFileName(elm) {
   var fn = $(elm).val();
   var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
   alert(filename);
}

How to convert a string to JSON object in PHP

What @deceze said is correct, it seems that your JSON is malformed, try this:

{
    "Coords": [{
        "Accuracy": "30",
        "Latitude": "53.2778273",
        "Longitude": "-9.0121648",
        "Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
    }, {
        "Accuracy": "30",
        "Latitude": "53.2778273",
        "Longitude": "-9.0121648",
        "Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
    }, {
        "Accuracy": "30",
        "Latitude": "53.2778273",
        "Longitude": "-9.0121648",
        "Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
    }, {
        "Accuracy": "30",
        "Latitude": "53.2778339",
        "Longitude": "-9.0121466",
        "Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
    }, {
        "Accuracy": "30",
        "Latitude": "53.2778159",
        "Longitude": "-9.0121201",
        "Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
    }]
}

Use json_decode to convert String into Object (stdClass) or array: http://php.net/manual/en/function.json-decode.php

[edited]

I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?

assuming you have the following variable:

$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';

You should convert it to Object (stdClass):

$manage = json_decode($data);

But working with stdClass is more complicated than PHP-Array, then try this (use second param with true):

$manage = json_decode($data, true);

This way you can use array functions: http://php.net/manual/en/function.array.php

adding an item:

$manage = json_decode($data, true);

echo 'Before: <br>';
print_r($manage);

$manage['Coords'][] = Array(
    'Accuracy' => '90'
    'Latitude' => '53.277720488429026'
    'Longitude' => '-9.012038778269686'
    'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);

echo '<br>After: <br>';
print_r($manage);

remove first item:

$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);

any chance you want to save to json to a database or a file:

$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';

$manage = json_decode($data, true);

$manage['Coords'][] = Array(
    'Accuracy' => '90'
    'Latitude' => '53.277720488429026'
    'Longitude' => '-9.012038778269686'
    'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);

if (($id = fopen('datafile.txt', 'wb'))) {
    fwrite($id, json_encode($manage));
    fclose($id);
}

I hope I have understood your question.

Good luck.

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

"cannot resolve symbol R" in Android Studio

This problem is caused because of the naming of files in "res" or "drawable" folder. You can't use any capital letter for naming a resource file. So, check if there is any such file and rename it with small letters.

And, also, you can try this: Go to: File > Invalidate cache/restart

These options have worked for me.

What is the return value of os.system() in Python?

"On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent."

http://docs.python.org/library/os.html#os.system

There is no error, so the exit code is zero

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

If you are using version 2.2 and above of Android Studio then in Android Studio use Build ? Analyze APK then select AndroidManifest.xml file.

how to add css class to html generic control div?

You don't add the css file to the div, you add a class to it then put your import at the top of the HTML page like so:

<link href="../files/external.css" rel="stylesheet" type="text/css" />

Then add a class like the following to your code: 'myStyle'.

Then in the css file do something like:

.myStyle
{
   border-style: 1px solid #DBE0E4;
}

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

Well after doing some more searching I discovered the error may be related to other issues as invalid keystores, passwords etc.

I then remembered that I had set two VM arguments for when I was testing SSL for my network connectivity.

I removed the following VM arguments to fix the problem:

-Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456

Note: this keystore no longer exists so that's probably why the Exception.

Laravel stylesheets and javascript don't load for non-base routes

Better way to use like,

<link rel="stylesheet" href="{{asset('assets/libraries/css/app.css')}}">

Laravel - check if Ajax request

Those who prefer to use laravel helpers they can check if a request is ajax using laravel request() helper.

if(request()->ajax())
   // code

Create tap-able "links" in the NSAttributedString of a UILabel?

Here is a swift version of NAlexN's answer.

class TapabbleLabel: UILabel {

let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
var textStorage = NSTextStorage() {
    didSet {
        textStorage.addLayoutManager(layoutManager)
    }
}

var onCharacterTapped: ((label: UILabel, characterIndex: Int) -> Void)?

let tapGesture = UITapGestureRecognizer()

override var attributedText: NSAttributedString? {
    didSet {
        if let attributedText = attributedText {
            textStorage = NSTextStorage(attributedString: attributedText)
        } else {
            textStorage = NSTextStorage()
        }
    }
}

override var lineBreakMode: NSLineBreakMode {
    didSet {
        textContainer.lineBreakMode = lineBreakMode
    }
}

override var numberOfLines: Int {
    didSet {
        textContainer.maximumNumberOfLines = numberOfLines
    }
}

/**
 Creates a new view with the passed coder.

 :param: aDecoder The a decoder

 :returns: the created new view.
 */
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setUp()
}

/**
 Creates a new view with the passed frame.

 :param: frame The frame

 :returns: the created new view.
 */
override init(frame: CGRect) {
    super.init(frame: frame)
    setUp()
}

/**
 Sets up the view.
 */
func setUp() {
    userInteractionEnabled = true
    layoutManager.addTextContainer(textContainer)
    textContainer.lineFragmentPadding = 0
    textContainer.lineBreakMode = lineBreakMode
    textContainer.maximumNumberOfLines = numberOfLines
    tapGesture.addTarget(self, action: #selector(TapabbleLabel.labelTapped(_:)))
    addGestureRecognizer(tapGesture)
}

override func layoutSubviews() {
    super.layoutSubviews()
    textContainer.size = bounds.size
}

func labelTapped(gesture: UITapGestureRecognizer) {
    guard gesture.state == .Ended else {
        return
    }

    let locationOfTouch = gesture.locationInView(gesture.view)
    let textBoundingBox = layoutManager.usedRectForTextContainer(textContainer)
    let textContainerOffset = CGPoint(x: (bounds.width - textBoundingBox.width) / 2 - textBoundingBox.minX,
                                      y: (bounds.height - textBoundingBox.height) / 2 - textBoundingBox.minY)        
    let locationOfTouchInTextContainer = CGPoint(x: locationOfTouch.x - textContainerOffset.x,
                                                 y: locationOfTouch.y - textContainerOffset.y)
    let indexOfCharacter = layoutManager.characterIndexForPoint(locationOfTouchInTextContainer,
                                                                inTextContainer: textContainer,
                                                                fractionOfDistanceBetweenInsertionPoints: nil)

    onCharacterTapped?(label: self, characterIndex: indexOfCharacter)
}
}

You can then create an instance of that class inside your viewDidLoad method like this:

let label = TapabbleLabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[view]-|",
                                               options: [], metrics: nil, views: ["view" : label]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[view]-|",
                                               options: [], metrics: nil, views: ["view" : label]))

let attributedString = NSMutableAttributedString(string: "String with a link", attributes: nil)
let linkRange = NSMakeRange(14, 4); // for the word "link" in the string above

let linkAttributes: [String : AnyObject] = [
    NSForegroundColorAttributeName : UIColor.blueColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleSingle.rawValue,
    NSLinkAttributeName: "http://www.apple.com"]
attributedString.setAttributes(linkAttributes, range:linkRange)

label.attributedText = attributedString

label.onCharacterTapped = { label, characterIndex in
    if let attribute = label.attributedText?.attribute(NSLinkAttributeName, atIndex: characterIndex, effectiveRange: nil) as? String,
        let url = NSURL(string: attribute) {
        UIApplication.sharedApplication().openURL(url)
    }
}

It's better to have a custom attribute to use when a character is tapped. Now, it's the NSLinkAttributeName, but could be anything and you can use that value to do other things other than opening a url, you can do any custom action.

Xampp MySQL not starting - "Attempting to start MySQL service..."

if all solutions up did not work for you, make sure the service is running and not set to Disabled!
Go to Services from Control panel and open Services,
Search for Apache2.4 and mysql then switch it to enabled, in the column of status it should be switched to Running

Overlay with spinner

use a css3 class "spinner". It's more beautiful and you don't need .gif

enter image description here

.spinner {
   position: absolute;
   left: 50%;
   top: 50%;
   height:60px;
   width:60px;
   margin:0px auto;
   -webkit-animation: rotation .6s infinite linear;
   -moz-animation: rotation .6s infinite linear;
   -o-animation: rotation .6s infinite linear;
   animation: rotation .6s infinite linear;
   border-left:6px solid rgba(0,174,239,.15);
   border-right:6px solid rgba(0,174,239,.15);
   border-bottom:6px solid rgba(0,174,239,.15);
   border-top:6px solid rgba(0,174,239,.8);
   border-radius:100%;
}

@-webkit-keyframes rotation {
   from {-webkit-transform: rotate(0deg);}
   to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
   from {-moz-transform: rotate(0deg);}
   to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
   from {-o-transform: rotate(0deg);}
   to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
   from {transform: rotate(0deg);}
   to {transform: rotate(359deg);}
}

Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit

You can find a lot of css spinners like this here : http://cssload.net/en/spinners/

NameError: name 'self' is not defined

Default argument values are evaluated at function define-time, but self is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.

It's a common pattern to default an argument to None and add a test for that in code:

def p(self, b=None):
    if b is None:
        b = self.a
    print b

Installing Apple's Network Link Conditioner Tool

Update on the answer December 2019 Xcode 11.1.2

Apple has moved Network Link Conditioner Tool to additional tools for Xcode

Go to the below link

https://developer.apple.com/download/more/?q=Additional%20Tools

enter image description here

Install the dmg file, select hardware from installer

enter image description here

select Network Link conditioner prefpane enter image description here

How to change default JRE for all Eclipse workspaces?

Finally got it: The way Eclipse picks up the JRE is using the system's PATH.

I did not have C:\home\SFTWR\jdk1.6.0_21\bin in the path at all before and I did have C:\Program Files (x86)\Java\jre6\bin. I had both JRE_HOME and JAVA_HOME set to C:\home\SFTWR\jdk1.6.0_21 but neither of those two mattered. I guess Eclipse did (something to the effect of) where java (or which on UNIX/Linux) to see where Java is in the path and took the JRE to which that java.exe belonged. In my case, despite all the configuration tweaks I had done (including eclipse.ini -vm option as suggested above), it remained stuck to what was in the path.

I removed the old JRE bin from the path, put the new one in, and it works for all workspaces.

Converting java.util.Properties to HashMap<String,String>

The problem is that Properties implements Map<Object, Object>, whereas the HashMap constructor expects a Map<? extends String, ? extends String>.

This answer explains this (quite counter-intuitive) decision. In short: before Java 5, Properties implemented Map (as there were no generics back then). This meant that you could put any Object in a Properties object. This is still in the documenation:

Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.

To maintain compatibility with this, the designers had no other choice but to make it inherit Map<Object, Object> in Java 5. It's an unfortunate result of the strive for full backwards compatibility which makes new code unnecessarily convoluted.

If you only ever use string properties in your Properties object, you should be able to get away with an unchecked cast in your constructor:

Map<String, String> map = new HashMap<String, String>( (Map<String, String>) properties);

or without any copies:

Map<String, String> map = (Map<String, String>) properties;

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Counting words in string

If you want to count specific words

function countWholeWords(text, keyword) {
    const times = text.match(new RegExp(`\\b${keyword}\\b`, 'gi'));

    if (times) {
        console.log(`${keyword} occurs ${times.length} times`);
    } else {
        console.log(keyword + " does not occurs")
    }
}


const text = `
In a professional context it often happens that private or corporate clients corder a publication to be 
made and presented with the actual content still not being ready. Think of a news blog that's 
filled with content hourly on the day of going live. However, reviewers tend to be distracted 
by comprehensible content, say, a random text copied from a newspaper or the internet.
`

const wordsYouAreLookingFor = ["random", "cat", "content", "reviewers", "dog", "with"]

wordsYouAreLookingFor.forEach((keyword) => countWholeWords(text, keyword));


// random occurs 1 times
// cat does not occurs
// content occurs 3 times
// reviewers occurs 1 times
// dog does not occurs
// with occurs 2 times

ClassCastException, casting Integer to Double

I think the main problem is that you are casting using wrapper class, seems that they are incompatible types.

But another issue is that "i" is an int so you are casting the final result and you should cast i as well. Also try using the keyword "double" to cast and not "Double" wrapper class.

You can check here:

Hope this helps. I found the thread useful but I think this helps further clarify it.

How can I enable CORS on Django REST Framework

The link you referenced in your question recommends using django-cors-headers, whose documentation says to install the library

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
)

Please browse the configuration section of its documentation, paying particular attention to the various CORS_ORIGIN_ settings. You'll need to set some of those based on your needs.

What's the best strategy for unit-testing database-driven applications?

I've actually used your first approach with quite some success, but in a slightly different ways that I think would solve some of your problems:

  1. Keep the entire schema and scripts for creating it in source control so that anyone can create the current database schema after a check out. In addition, keep sample data in data files that get loaded by part of the build process. As you discover data that causes errors, add it to your sample data to check that errors don't re-emerge.

  2. Use a continuous integration server to build the database schema, load the sample data, and run tests. This is how we keep our test database in sync (rebuilding it at every test run). Though this requires that the CI server have access and ownership of its own dedicated database instance, I say that having our db schema built 3 times a day has dramatically helped find errors that probably would not have been found till just before delivery (if not later). I can't say that I rebuild the schema before every commit. Does anybody? With this approach you won't have to (well maybe we should, but its not a big deal if someone forgets).

  3. For my group, user input is done at the application level (not db) so this is tested via standard unit tests.

Loading Production Database Copy:
This was the approach that was used at my last job. It was a huge pain cause of a couple of issues:

  1. The copy would get out of date from the production version
  2. Changes would be made to the copy's schema and wouldn't get propagated to the production systems. At this point we'd have diverging schemas. Not fun.

Mocking Database Server:
We also do this at my current job. After every commit we execute unit tests against the application code that have mock db accessors injected. Then three times a day we execute the full db build described above. I definitely recommend both approaches.

What do pty and tty mean?

A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.

A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.

For example, when you ssh in to a machine and run ls, the ls command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.

Your content must have a ListView whose id attribute is 'android.R.id.list'

Exact way I fixed this based on feedback above since I couldn't get it to work at first:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.preferences);

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
    android:key="upgradecategory"
    android:title="Upgrade" >
    <Preference
        android:key="download"
        android:title="Get OnCall Pager Pro"
        android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>

Generic Property in C#

You can make a generic class like this:

public class MyProp<T>
{
    private T _value;

    public T Value
    {
        get
        {
            // insert desired logic here
            return _value;
        }
        set
        {
            // insert desired logic here
            _value = value;
        }
    }

    public static implicit operator T(MyProp<T> value)
    {
        return value.Value;
    }

    public static implicit operator MyProp<T>(T value)
    {
        return new MyProp<T> { Value = value };
    }
}

...then use it in a class like so:

class SomeClass
{
    public MyProp<int> SomeProperty { get; set; }
}

The implicit operators means that you do not need to explicitly set or get the Value property of MyProp, but can write code to access the value in a more "natural" way:

SomeClass instance = new SomeClass();
instance.SomeProperty = 32;
int someInt = instance.SomeProperty;

Lightweight Javascript DB for use in Node.js

Take a look at http://www.tingodb.com. I believe it does what you looking for. Additionally it fully compatible with MongoDB API. This reduces implementation risks and gives you option to switch to heavy solution as your app grows.

https://github.com/sergeyksv/tingodb

Populating a data frame in R in a loop

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

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

Example to illustrate the general approach:

mylist <- list() #create an empty list

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

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

Finally here is a vectorized alternative to the example loop:

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

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

Why can't I define a default constructor for a struct in .NET?

public struct Rational 
{
    private long numerator;
    private long denominator;

    public Rational(long num = 0, long denom = 1)   // This is allowed!!!
    {
        numerator   = num;
        denominator = denom;
    }
}

Customizing the template within a Directive

Here's what I ended up using.

I'm very new to AngularJS, so would love to see better / alternative solutions.

angular.module('formComponents', [])
    .directive('formInput', function() {
        return {
            restrict: 'E',
            scope: {},
            link: function(scope, element, attrs)
            {
                var type = attrs.type || 'text';
                var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
                var htmlText = '<div class="control-group">' +
                    '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                        '<div class="controls">' +
                        '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                        '</div>' +
                    '</div>';
                element.html(htmlText);
            }
        }
    })

Example usage:

<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>

What does AND 0xFF do?

Anding an integer with 0xFF leaves only the least significant byte. For example, to get the first byte in a short s, you can write s & 0xFF. This is typically referred to as "masking". If byte1 is either a single byte type (like uint8_t) or is already less than 256 (and as a result is all zeroes except for the least significant byte) there is no need to mask out the higher bits, as they are already zero.

See tristopiaPatrick Schlüter's answer below when you may be working with signed types. When doing bitwise operations, I recommend working only with unsigned types.

Format numbers in thousands (K) in Excel

I've found the following combination that works fine for positive and negative numbers (43787200020 is transformed to 43.787.200,02 K)

[>=1000] #.##0,#0. "K";#.##0,#0. "K"

Store output of sed into a variable

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

Remove shadow below actionbar

Use:

outLineAmbientShadowColor="@null"

Get a list of distinct values in List

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

Adding new files to a subversion repository

Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:

svn add directory_name

will add the directory directory_name and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html

What is dtype('O'), in pandas?

'O' stands for object.

#Loading a csv file as a dataframe
import pandas as pd 
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'

#Checking the datatype of column name
train_df[col_name].dtype

#Instead try printing the same thing
print train_df[col_name].dtype

The first line returns: dtype('O')

The line with the print statement returns the following: object

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

Carriage Return\Line feed in Java

Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.

How should I escape strings in JSON?

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

How to Automatically Close Alerts using Twitter Bootstrap

This is the coffescript version:

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000

How to markdown nested list items in Bitbucket?

Possibilities

  • It is possible to nest a bulleted-unnumbered list into a higher numbered list.
  • But in the bulleted-unnumbered list the automatically numbered list will not start: Its is not supported.
    • To start a new numbered list after a bulleted-unnumbered one, put a piece of text between them, or a subtitle: A new numbered list cannot start just behind the bulleted: The interpreter will not start the numbering.

in practice

  1. Dog

    1. German Shepherd - with only a single space ahead.
    2. Belgian Shepherd - max 4 spaces ahead.
      • Number in front of a line interpreted as a "numbering bullet", so making the indentation.
        • ..and ignores the written digit: Places/generates its own, in compliance with the structure.
        • So it is OK to use only just "1" ones, to get your numbered list.
          • Or whatever integer number, even of more digits: The list numbering will continue by increment ++1.
        • However, the first item in the numbered list will be kept, so the first leading will usually be the number "1".
    3. Malinois - 5 spaces makes 3rd level already.
      1. MalinoisB - 5 spaces makes 3rd level already.
      2. Groenendael - 8 spaces makes 3rd level yet too.
        1. Tervuren - 9 spaces for 4th level - Intentionaly started by "55".
        2. TervurenB - numbered by "88", in the source code.
  2. Cat

    1. Siberian; a. SiberianA - problem reproduced: letters (i.e. "a" here) not recognized by the interpreter as "numbering".
      • No matter, it is indented to its separated line, in the source code.
    2. Siamese
      • a. so written manually as a workaround misusing bullets, unnumbered list.

127 Return code from $?

Generally it means:

127 - command not found

but it can also mean that the command is found,
but a library that is required by the command is NOT found.

Adding images to an HTML document with javascript

or you can just

<script> 
document.write('<img src="/*picture_location_(you can just copy the picture and paste   it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>

How to capitalize first letter of each word, like a 2-word city?

You can use CSS:

p.capitalize {text-transform:capitalize;}

Update (JS Solution):

Based on Kamal Reddy's comment:

document.getElementById("myP").style.textTransform = "capitalize";

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);