Programs & Examples On #Server to server

Communications between a server and server.

How to programmatically set the SSLContext of a JAX-WS client?

The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.

Here is my workaround for this:

Set you SSLSocketFactory as default:

HttpsURLConnection.setDefaultSSLSocketFactory(...);

For Apache CXF which I use you need also add these lines to your config:

<http-conf:conduit name="*.http-conduit">
  <http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>

Plotting with C#

gnuplot is an actively maintained program widely used in the scientific community. Normally plots are generated from data files which you can write out in your C# program, but it is also possible to call the gnuplot executable from C# and display the generated image in a C# picture box.

Update a column in MySQL

You have to use UPDATE instead of INSERT:

For Example:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

For Linux users (I'm using a Debian Distro, Kali) Here's how I resolved mine.

If you don't already have jdk-8, you want to get it at oracle's site

https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

I got the jdk-8u191-linux-x64.tar.gz

Step 1 - Installing Java Move and unpack it at a suitable location like so

$ mv jdk-8u191-linux-x64.tar.gz /suitablelocation/
$ tar -xzvf /suitablelocation/jdk-8u191-linux-x64.tar.gz

You should get an unzipped folder like jdk1.8.0_191 You can delete the tarball afterwards to conserve space

Step 2 - Setting up alternatives to the default java location

$ update-alternatives --install /usr/bin/java java /suitablelocation/jdk1.8.0_191/bin/java 1
$ update-alternatives --install /usr/bin/javac javac /suitablelocation/jdk1.8.0_191/bin/javac 1

Step 3 - Selecting your alternatives as default

$ update-alternatives --set java /suitablelocation/jdk1.8.0_191/bin/java
$ update-alternatives --set javac /suitablelocation/jdk1.8.0_191/bin/javac

Step 4 - Confirming default java version

$ java -version

Notes

  1. In the original article here: https://forums.kali.org/showthread.php?41-Installing-Java-on-Kali-Linux, the default plugin for mozilla was also set. I assume we don't really need the plugins as we're simply trying to develop for android.
  2. As in @spassvogel's answer, you should also place a @repositories.cfg file in your ~/.android directory as this is needed to update the tools repo lists
  3. Moving some things around may require root authority. Use sudo wisely.
  4. For sdkmanager usage, see official guide: https://developer.android.com/studio/command-line/sdkmanager

How to add border radius on table row

All the answers are way too long. The easiest way to add border radius to a table element that accepts border as a property, is doing border radius with overflow: hidden.

border: xStyle xColor xSize;
border-collapse: collapse;
border-radius: 1em;
overflow: hidden;

How do I make background-size work in IE?

There is a good polyfill for that: louisremi/background-size-polyfill

To quote the documentation:

Upload backgroundsize.min.htc to your website, along with the .htaccess that will send the mime-type required by IE (Apache only — it's built in nginx, node and IIS).

Everywhere you use background-size in your CSS, add a reference to this file.

.selector { 
    background-size: cover;
    /* The url is relative to the document, not to the css file! */
    /* Prefer absolute urls to avoid confusion. */
    -ms-behavior: url(/backgroundsize.min.htc);
}

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

ASP.NET MVC Global Variables

For non-static variables, I sorted it out via Application class dictionary as below:

At Global.asax.ac:

namespace MvcWebApplication 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

    public class MvcApplication : System.Web.HttpApplication 
    { 
        private string _licensefile; // the global private variable

        internal string LicenseFile // the global controlled variable
        { 
            get 
            { 
                if (String.IsNullOrEmpty(_licensefile)) 
                { 
                    string tempMylFile = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(LDLL.License)).Location), "License.l"); 
                    if (!File.Exists(tempMylFile)) 
                        File.Copy(Server.MapPath("~/Content/license/License.l"), 
                            tempMylFile, 
                            true); 
                    _licensefile = tempMylFile; 
                } 
                return _licensefile; 
            } 
        }
        protected void Application_Start()
        {
            Application["LicenseFile"] = LicenseFile;// the global variable's bed

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

And in Controller:

namespace MvcWebApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(HttpContext.Application["LicenseFile"] as string);
        }

    }
}

In this way we can have global variables in ASP.NET MVC :)

NOTE: If your object is not string simply write:

return View(HttpContext.Application["X"] as yourType);

Proper use of 'yield return'

I tend to use yield-return when I calculate the next item in the list (or even the next group of items).

Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.

Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In your particular example, you have the full list of products, so I'd use Version 2.

The requested operation cannot be performed on a file with a user-mapped section open

Others have already established that this error is due to another application having a lock on the file. Just wanted to point out that git diff locks files as well until you quit out of it. That's what caused this in my case.

Easy way to print Perl array? (with a little formatting)

Using Data::Dumper :

use strict;
use Data::Dumper;

my $GRANTstr = 'SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE, TRIGGER';
$GRANTstr    =~ s/, /,/g;
my @GRANTs   = split /,/ , $GRANTstr;

print Dumper(@GRANTs) . "===\n\n";

print Dumper(\@GRANTs) . "===\n\n";

print Data::Dumper->Dump([\@GRANTs], [qw(GRANTs)]);

Generates three different output styles:

$VAR1 = 'SELECT';
$VAR2 = 'INSERT';
$VAR3 = 'UPDATE';
$VAR4 = 'DELETE';
$VAR5 = 'LOCK TABLES';
$VAR6 = 'EXECUTE';
$VAR7 = 'TRIGGER';
===

$VAR1 = [
          'SELECT',
          'INSERT',
          'UPDATE',
          'DELETE',
          'LOCK TABLES',
          'EXECUTE',
          'TRIGGER'
        ];
===

$GRANTs = [
            'SELECT',
            'INSERT',
            'UPDATE',
            'DELETE',
            'LOCK TABLES',
            'EXECUTE',
            'TRIGGER'
          ];

Creating a daemon in Linux

I can stop at the first requirement "A daemon which cannot be stopped ..."

Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.

http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring

All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.

Best way to concatenate List of String objects?

I prefer String.join(list) in Java 8

How to build jars from IntelliJ properly?

This is still an issue in 2017, I hope it will help somebody out there! I found 2 possibilities to create working jar-s under IntelliJ 2017.2

1. Creating artifact from IntelliJ:

  • Go to project structure:

File menu

  • Create a new artifact:

Create a new artifact

  • Select the main class, and be sure to change the manifest folder:

enter image description here

You have to change manifest directory:

<project folder>\src\main\java 

replace "java" with "resources"

<project folder>\src\main\resources

This is how it should look like:

correct way for new manifest

  • Then you choose the dependencies what you want to be packed IN your jar, or NEAR your jar file

  • To build your artifact go to build artifacts and choose "rebuild". It will create an "out" folder with your jar file and its dependencies.

enter image description here

2. Using maven-assembly-plugin

Add build section to the pom file

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <finalName>ServiceCreate</finalName>
                    <appendAssemblyId>false</appendAssemblyId>
                    <archive>
                        <manifest>
                            <mainClass>com.svt.optimoo.App</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • Create a new run/debug configuration:

Create a new run/debug configuration:

  • Choose application:

Choose application

  • Fill in the form
  • Add the "assembly:single" maven goal after build to be executed last

enter image description here

Final setup

  • Save it, then run

enter image description here

This procedure will create the jar file under the "target" folder

JAR file location

How to make inactive content inside a div?

Using jquery you might do something like this:

// To disable 
$('#targetDiv').children().attr('disabled', 'disabled');

// To enable
$('#targetDiv').children().attr('enabled', 'enabled');

Here's a jsFiddle example: http://jsfiddle.net/monknomo/gLukqygq/

You could also select the target div's children and add a "disabled" css class to them with different visual properties as a callout.

//disable by adding disabled class
$('#targetDiv').children().addClass("disabled");

//enable by removing the disabled class
$('#targetDiv').children().removeClass("disabled");

Here's a jsFiddle with the as an example: https://jsfiddle.net/monknomo/g8zt9t3m/

Using SVG as background image

With my solution you're able to get something similar:

svg background image css

Here is bulletproff solution:

Your html: <input class='calendarIcon'/>

Your SVG: i used fa-calendar-alt

fa-calendar-alt

(any IDE may open svg image as shown below)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>

To use it at css background-image you gotta encode the svg to address valid string. I used this tool

As far as you got all stuff you need, you're coming to css

.calendarIcon{
      //your url will be something like this:
      background-image: url("data:image/svg+xml,***<here place encoded svg>***");
      background-repeat: no-repeat;
    }

Note: these styling wont have any effect on encoded svg image

.{
      fill: #f00; //neither this
      background-color: #f00; //nor this
}

because all changes over the image must be applied directly to its svg code

<svg xmlns="" path="" fill="#f00"/></svg>

To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:

.calendarIcon{
      background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
      background-repeat: no-repeat;
      padding-right: calc(1.5em + 0.75rem);
      background-position: center right calc(0.375em + 0.1875rem);
      background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
    }

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use a ComboBox with its ComboBoxStyle (appears as DropDownStyle in later versions) set to DropDownList. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx

Get all variables sent with POST?

Using this u can get all post variable

print_r($_POST)

How do I find the version of Apache running without access to the command line?

Rarely, a hardened HTTP server is configured to give no server information or misleading server information. In those scenarios if the server has PHP enabled you can add:

<?php phpinfo(); ?>

in a file and browse to it and look for the

_SERVER["SERVER_SOFTWARE"]

entry. This is susceptible to the same hardening lack of information/misleading though I would imagine that it's not altered often, because this method first requires access to the machine to create the PHP file.

Making authenticated POST requests with Spring RestTemplate for Android

I was recently dealing with an issue when I was trying to get past authentication while making a REST call from Java, and while the answers in this thread (and other threads) helped, there was still a bit of trial and error involved in getting it working.

What worked for me was encoding credentials in Base64 and adding them as Basic Authorization headers. I then added them as an HttpEntity to restTemplate.postForEntity, which gave me the response I needed.

Here's the class I wrote for this in full (extending RestTemplate):

public class AuthorizedRestTemplate extends RestTemplate{

    private String username;
    private String password;

    public AuthorizedRestTemplate(String username, String password){
        this.username = username;
        this.password = password;
    }

    public String getForObject(String url, Object... urlVariables){
        return authorizedRestCall(this, url, urlVariables);
    }

    private String authorizedRestCall(RestTemplate restTemplate, 
            String url, Object... urlVariables){
        HttpEntity<String> request = getRequest();
        ResponseEntity<String> entity = restTemplate.postForEntity(url, 
                request, String.class, urlVariables);
        return entity.getBody();
    }

    private HttpEntity<String> getRequest(){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + getBase64Credentials());
        return new HttpEntity<String>(headers);
    }

    private String getBase64Credentials(){
        String plainCreds = username + ":" + password;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}

How to display the value of the bar on each bar with pyplot.barh()?

Use plt.text() to put text in the plot.

Example:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

This will show the figure as:

bar chart with values at the top

How do I clone a generic list in C#?

If your elements are value types, then you can just do:

List<YourType> newList = new List<YourType>(oldList);

However, if they are reference types and you want a deep copy (assuming your elements properly implement ICloneable), you could do something like this:

List<ICloneable> oldList = new List<ICloneable>();
List<ICloneable> newList = new List<ICloneable>(oldList.Count);

oldList.ForEach((item) =>
    {
        newList.Add((ICloneable)item.Clone());
    });

Obviously, replace ICloneable in the above generics and cast with whatever your element type is that implements ICloneable.

If your element type doesn't support ICloneable but does have a copy-constructor, you could do this instead:

List<YourType> oldList = new List<YourType>();
List<YourType> newList = new List<YourType>(oldList.Count);

oldList.ForEach((item)=>
    {
        newList.Add(new YourType(item));
    });

Personally, I would avoid ICloneable because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like YourType.CopyFrom(YourType itemToCopy) that returns a new instance of YourType.

Any of these options could be wrapped by a method (extension or otherwise).

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

Java converting int to hex and back again

int val = -32768;
String hex = Integer.toHexString(val);

int parsedResult = (int) Long.parseLong(hex, 16);
System.out.println(parsedResult);

That's how you can do it.

The reason why it doesn't work your way: Integer.parseInt takes a signed int, while toHexString produces an unsigned result. So if you insert something higher than 0x7FFFFFF, an error will be thrown automatically. If you parse it as long instead, it will still be signed. But when you cast it back to int, it will overflow to the correct value.

dyld: Library not loaded ... Reason: Image not found

In the target's General tab, there is a section called Frameworks, Libraries, and Embedded Content

Click on the + sign, add required framework and the crash is resolved.

Update latest xcode screen-shot

jQuery UI tabs. How to select a tab based on its id not based on index

Active 1st tab

$("#workflowTab").tabs({ active: 0 });

Active last tab

$("#workflowTab").tabs({ active: -1 });

Active 2nd tab

$("#workflowTab").tabs({ active: 1 });

Its work like an array

Dynamically adding HTML form field using jQuery

This will insert a new element after the input field with id "password".

$(document).ready(function(){
  var newInput = $("<input name='new_field' type='text'>");
  $('input#password').after(newInput);
});

Not sure if this answers your question.

How can I find the number of arguments of a Python function?

As other answers suggest, getargspec works well as long as the thing being queried is actually a function. It does not work for built-in functions such as open, len, etc, and will throw an exception in such cases:

TypeError: <built-in function open> is not a Python function

The below function (inspired by this answer) demonstrates a workaround. It returns the number of args expected by f:

from inspect import isfunction, getargspec
def num_args(f):
  if isfunction(f):
    return len(getargspec(f).args)
  else:
    spec = f.__doc__.split('\n')[0]
    args = spec[spec.find('(')+1:spec.find(')')]
    return args.count(',')+1 if args else 0

The idea is to parse the function spec out of the __doc__ string. Obviously this relies on the format of said string so is hardly robust!

in python how do I convert a single digit number into a double digits string?

Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.

My approach is to leave number as a number until the moment you want to convert it into string:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Similar to David Hall's response, if you are a non-coder, it may be easiest to right-click within results, then choose Pane > Criteria. This allows you to adjust sort, add filters, etc... without adjusting SQL code.

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

What is an opaque response, and what purpose does it serve?

Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.

This is what { mode: 'no-cors' } was made for.

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

How can you represent inheritance in a database?

I lean towards method #1 (a unified Section table), for the sake of efficiently retrieving entire policies with all their sections (which I assume your system will be doing a lot).

Further, I don't know what version of SQL Server you're using, but in 2008+ Sparse Columns help optimize performance in situations where many of the values in a column will be NULL.

Ultimately, you'll have to decide just how "similar" the policy sections are. Unless they differ substantially, I think a more-normalized solution might be more trouble than it's worth... but only you can make that call. :)

VideoView Full screen in android application

whether you want to keep the aspect ratio of a video or stretch it to fill its parent area, using the right layout manager can get the job done.

Keep the aspect ratio :

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

<VideoView
  android:id="@+id/videoView"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_gravity="center"/>

</LinearLayout>

!!! To fill in the field:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <VideoView android:id="@+id/videoViewRelative"
         android:layout_alignParentTop="true"
         android:layout_alignParentBottom="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentRight="true"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">
    </VideoView>

</RelativeLayout>

Specific Time Range Query in SQL Server

you can try this (I don't have sql server here today so I can't verify syntax, sorry)

select attributeName
  from tableName
 where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
   and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
   and DATEPART(day,attributeName) BETWEEN 2 AND 4

Is there an opposite of include? for Ruby Arrays?

How about the following:

unless @players.include?(p.name)
  ....
end

How to delete last item in list?

just simply use list.pop() now if you want it the other way use : list.popleft()

Update query PHP MySQL

<?php
require 'db_config.php';


  $id  = $_POST["id"];
  $post = $_POST;

  $sql = "UPDATE items SET title = '".$post['title']."'

    ,description = '".$post['description']."' 

    WHERE id = '".$id."'";

  $result = $mysqli->query($sql);


  $sql = "SELECT * FROM items WHERE id = '".$id."'"; 

  $result = $mysqli->query($sql);

  $data = $result->fetch_assoc();


echo json_encode($data);
?>

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

How can I get the full/absolute URL (with domain) in Django?

If anyone is interested in fetching the absolute reverse url with parameters in a template , the cleanest way is to create your own absolute version of the {% url %} template tag by extending and using existing default code.

Here is my code:

from django import template
from django.template.defaulttags import URLNode, url

register = template.Library()

class AbsURLNode(URLNode):
    def __init__(self, view_name, args, kwargs, asvar):
        super().__init__(view_name, args, kwargs, asvar)

    def render(self, context):
        url     = super().render(context)
        request = context['request']

        return request.build_absolute_uri(url)


@register.tag
def abs_url(parser, token):

    urlNode = url(parser, token)
    return AbsURLNode( urlNode.view_name, urlNode.args, urlNode.kwargs, urlNode.asvar  )

Usage in templates:

{% load wherever_your_stored_this_tag_file %}
{% abs_url 'view_name' parameter %}

will render(example):

http://example.com/view_name/parameter/

instead of

/view_name/parameter/

Javascript communication between browser tabs/windows

Found different way using HTML5 localstorage, I've create a library with events like API:

sysend.on('foo', function(message) {
    console.log(message);
});
var input = document.getElementsByTagName('input')[0];
document.getElementsByTagName('button')[0].onclick = function() {
    sysend.broadcast('foo', {message: input.value});
};

it will send messages to all other pages but not for current one.

How to change or add theme to Android Studio?

File->Settings->Editor->Colors & Fonts-> In scheme name select Darcula and apply to see a awesome dark background theme editor

Android Studio 3.1.2 File->Settings->Editor->Color Scheme-> In scheme name select Darcula and apply to see a awesome dark background theme editor

Using RegEx in SQL Server

A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;

using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString Regex(string input, string regex)
 {
  var match = RX.Regex.Match(input, regex).Groups[1].Value;
  return new SqlString (match);
 }
}

Installation instructions can be found here

How do I update/upsert a document in Mongoose?

Mongoose now supports this natively with findOneAndUpdate (calls MongoDB findAndModify).

The upsert = true option creates the object if it doesn't exist. defaults to false.

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

In older versions Mongoose does not support these hooks with this method:

  • defaults
  • setters
  • validators
  • middleware

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Specifying and saving a figure with exact size in pixels

plt.imsave worked for me. You can find the documentation here: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.imsave.html

#file_path = directory address where the image will be stored along with file name and extension
#array = variable where the image is stored. I think for the original post this variable is im_np
plt.imsave(file_path, array)

How can I print the contents of a hash in Perl?

Data::Dumper is your friend.

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

Object comparison in JavaScript

Here is my ES3 commented solution (gory details after the code):

function object_equals( x, y ) {
  if ( x === y ) return true;
    // if both x and y are null or undefined and exactly the same

  if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
    // if they are not strictly equal, they both need to be Objects

  if ( x.constructor !== y.constructor ) return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

  for ( var p in x ) {
    if ( ! x.hasOwnProperty( p ) ) continue;
      // other properties were tested using x.constructor === y.constructor

    if ( ! y.hasOwnProperty( p ) ) return false;
      // allows to compare x[ p ] and y[ p ] when set to undefined

    if ( x[ p ] === y[ p ] ) continue;
      // if they have the same strict value or identity then they are equal

    if ( typeof( x[ p ] ) !== "object" ) return false;
      // Numbers, Strings, Functions, Booleans must be strictly equal

    if ( ! object_equals( x[ p ],  y[ p ] ) ) return false;
      // Objects and Arrays must be tested recursively
  }

  for ( p in y )
    if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
      return false;
        // allows x[ p ] to be set to undefined

  return true;
}

In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.

First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.

Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.

Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.

The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.

The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.

Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.

No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.

Overall this code handles most corner cases in only 16 lines of code (without comments).


Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

Concatenating two std::vectors

Or you could use:

std::copy(source.begin(), source.end(), std::back_inserter(destination));

This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of std::back_inserter to convert from one type to the other.

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM) 

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)

further,

char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature

Python: avoid new line with print command

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere

How to output to the console in C++/Windows

Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated.

So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advice here. Either freopen stdout and stderr with "CON", or do the other linker/compile workarounds there.

In case the link gets broken again, here is exactly what was referenced from libSDL:

How do I avoid creating stdout.txt and stderr.txt?

"I believe inside the Visual C++ project that comes with SDL there is a SDL_nostdio target > you can build which does what you want(TM)."

"If you define "NO_STDIO_REDIRECT" and recompile SDL, I think it will fix the problem." > > (Answer courtesy of Bill Kendrick)

How to change XML Attribute

If the attribute you want to change doesn't exist or has been accidentally removed, then an exception occurs. I suggest you first create a new attribute and send it to a function like the following:

private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList)
    {
        foreach (var attr in attrList)
        {
            if (node.Attributes[attr.Name] != null)
            {
                node.Attributes[attr.Name].Value = attr.Value;
            }
            else
            {
                node.Attributes.Append(attr);
            }
        }
    }

Usage:

   XmlAttribute attr = dom.CreateAttribute("name");
   attr.Value = value;
   SetAttrSafe(node, attr);

How to use the IEqualityComparer

The inclusion of your comparison class (or more specifically the AsEnumerable call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.

You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.

Bootstrap with jQuery Validation Plugin

For the bootstrap 4 beta were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.

First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using

.fa.valid-feedback,
.fa.invalid-feedback {
    position: absolute;
    right: 25px;
    margin-top: -50px;
    z-index: 2;
    display: block;
    pointer-events: none;
}

.fa.valid-feedback {
    margin-top: -28px;
}

The classes have also changed as the beta uses the 'state' of the control rather than classes which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks

$(element).closest('form').addClass('was-validated');

I would also recommend using the new element and classes for form control help text

errorElement: 'small',
errorClass: 'form-text invalid-feedback',

Using ls to list directories and their total sizes

If you want more control over the size that you want to list the directories over, you can use the threshold (-t) switch as in:

$ du -ht 1000000000 | sort --reverse

du - disk usage
h - human readable format
t - threshold size

Here, we want to list all directories which are greater than 1GB in size.

$ du -ht 1G | sort --reverse

Explanation:

Units that are described in wiki follows:

K, M, G, T, P, E, Z, Y (powers of 1024) or
KB, MB, GB, TB, PB, EB, ZB, YB (powers of 1000).

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

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

I faced the same issue in Android Studio version 3.5.3. This is how i fixed it.

I updated the dependecy com.android.tools.build:gradle in my project level build.gradle file from a lower version to 3.5.3 as below.

classpath 'com.android.tools.build:gradle:3.5.3'

I then went ahead and edited the value of distributionUrl in gradle-wrapper.properties file as below. This file is in the directory /gradle/wrapper/ from the root of your project folder.

distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

.NET HttpClient. How to POST string value?

You could do something like this

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:6740/api/Membership/exist");

req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";         
req.ContentLength = 6;

StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();

And then strReponse should contain the values returned by your webservice

How to verify that a specific method was not called using Mockito?

Both the verifyNoMoreInteractions() and verifyZeroInteractions() method internally have the same implementation as:

public static transient void verifyNoMoreInteractions(Object mocks[])
{
    MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}

public static transient void verifyZeroInteractions(Object mocks[])
{
    MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}

so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.

How to Serialize a list in java?

As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.

Django DoesNotExist

This line

 except Vehicle.vehicledevice.device.DoesNotExist

means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like

 except Device.DoesNotExist

How can I fill out a Python string with spaces?

Use Python 2.7's mini formatting for strings:

'{0: <8}'.format('123')

This left aligns, and pads to 8 characters with the ' ' character.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

Solving this problem is much more within reach nowadays. The HTML5 History API allows us to manipulate the location bar to display any URL within the current domain.

function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}

Working demo: http://jsfiddle.net/AndyE/ycmPt/show/

This works in Chrome 9, Firefox 4, Safari 5, Opera 11.50 and in IE 10. For unsupported browsers, you could always write a gracefully degrading script that makes use of it where available:

function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

So you can get rid of the hash symbol, just not in all browsers — yet.

Note: if you want to replace the current page in the browser history, use replaceState() instead of pushState().

Have bash script answer interactive prompts

In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh

I was needing to answer some questions for a doctrine schema exporter so my file looked like this.

-- This is an example only --

php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format`                                     1
`#Would you like to change the setup configuration before exporting`        y
`#Log to console`                                                           y
`#Log file`                                                                 testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]`                                          y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF

The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).

to run the script simply be in the directory you want and run 'sh autocomplete.sh' in terminal.

In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.

My example just shows how this can be done with comments also using the ` character so you remember what each step is.

Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!

Hope this helps someone out.

How can I use tabs for indentation in IntelliJ IDEA?

For anyone not able to get this, another thing you need to uncheck the following as well

Preferences > Editor > Code Style
[] Enable EditorConfig support
EditorConfig may override the IDE code style settings

My IntelliJ version 15.0.4

curl POST format for CURLOPT_POSTFIELDS

Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');

Just another way, and it works very well.

Avoid printStackTrace(); use a logger call instead

The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.

How to change btn color in Bootstrap

I am not the OP of this answer but it helped me so:

I wanted to change the color of the next/previous buttons of the bootstrap carousel on my homepage.

Solution: Copy the selector names from bootstrap.css and move them to your own style.css (with your own prefrences..) :

_x000D_
_x000D_
.carousel-control-prev-icon,
.carousel-control-next-icon {
  height: 100px;
  width: 100px;
  outline: black;
  background-size: 100%, 100%;
  border-radius: 50%;
  border: 1px solid black;
  background-image: none;
}

.carousel-control-next-icon:after
{
  content: '>';
  font-size: 55px;
  color: red;
}

.carousel-control-prev-icon:after {
  content: '<';
  font-size: 55px;
  color: red;
}
_x000D_
_x000D_
_x000D_

How can I list the scheduled jobs running in my database?

Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:

GRANT CREATE JOB TO scott;

After this statement is executed, scott can create jobs, schedules, or programs in his schema.

copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239

Node.js: for each … in not working

for (var i in conf) {
  val = conf[i];
  console.log(val.path);
}

CSS : center form in page horizontally and vertically

you can use display:flex to do this : http://codepen.io/anon/pen/yCKuz

html,body {
  height:100%;
  width:100%;
  margin:0;
}
body {
  display:flex;
}
form {
  margin:auto;/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
}

or display:table http://codepen.io/anon/pen/LACnF/

body, html {   
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    display:table;
}
body {
    display:table-cell;
    vertical-align:middle;
}
form {
    display:table;/* shrinks to fit content */
    margin:auto;
}

Install a Python package into a different directory using pip?

Just add one point to @Ian Bicking's answer:

Using the --user option to specify the installed directory also work if one wants to install some Python package into one's home directory (without sudo user right) on remote server.

E.g.,

pip install --user python-memcached

The command will install the package into one of the directories that listed in your PYTHONPATH.

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006) in vueJs

with the error:

 exportColumns.forEach(element=> {
      if (element.command !== undefined) {
        let d = element.command.findIndex(x => x.name === "destroy");

you can fixed it by defining thoes variables as any as follow.

corrected code:

exportColumns.forEach((element: any) => {
      if (element.command !== undefined) {
        let d = element.command.findIndex((x: any) => x.name === "destroy");

What does "while True" mean in Python?

In this context, I suppose it could be interpreted as

do
...
while cmd  != 'e' 

Onclick on bootstrap button

You can use 'onclick' attribute like this :

<a ... href="javascript: onclick();" ...>...</a>

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

For me, it worked as given below:

<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">

<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">

jQuery - replace all instances of a character in a string

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.

How to extract .war files in java? ZIP vs JAR

For mac users: in terminal command :

unzip yourWARfileName.war

How do I get the logfile from an Android device?

Often I get the error "logcat read: Invalid argument". I had to clear the log, before reading from the log.

I do like this:

prompt> cd ~/Desktop
prompt> adb logcat -c
prompt> adb logcat | tee log.txt

Difference between fprintf, printf and sprintf?

printf outputs to the standard output stream (stdout)

fprintf goes to a file handle (FILE*)

sprintf goes to a buffer you allocated. (char*)

Render partial from different folder (not shared)

Just include the path to the view, with the file extension.

Razor:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

How to create an HTML button that acts like a link?

Try

_x000D_
_x000D_
.abutton { 
  background: #bada55; padding: 5px; border-radius: 5px; 
  transition: 1s; text-decoration: none; color: black;
}
.abutton:hover { background: #2a2;  }
_x000D_
<a href="https://example.com" class="abutton">Continue</a>
_x000D_
_x000D_
_x000D_

Extract only right most n letters from a string

Null Safe Methods :

Strings shorter than the max length returning the original string

String Right Extension Method

public static string Right(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Reverse().Take(count).Reverse());

String Left Extension Method

public static string Left(this string input, int count) =>
    String.Join("", (input + "").ToCharArray().Take(count));

Javascript logical "!==" operator?

It's != without type coercion. See the MDN documentation for comparison operators.

Also see this StackOverflow answer, which includes a quote from "JavaScript: The Good Parts" about the problems with == and !=. (null == undefined, false == "0", etc.)

Short answer: always use === and !== unless you have a compelling reason to do otherwise. (Tools like JSLint, JSHint, ESLint, etc. will give you this same advice.)

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

How do I combine two data-frames based on two columns?

Hope this helps;

df1 = data.frame(CustomerId=c(1:10),
             Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
             Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))

df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1),   rep("Cal", 2)),
             like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))

df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))

Assuming df1$Hobby and df2$like mean the same thing.

How are booleans formatted in Strings in Python?

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.

Stretch and scale CSS background

This is what I've made of it. In the stretch class, I simply changed the height to auto. This way your background picture has always got the same size as the width of the screen and the height will allways have the right size.

#background {
    width: 100%;
    height: 100%;
    position: absolute;
    margin-left: 0px;
    margin-top: 0px;
    z-index: 0;
}

.stretch {
    width:100%;
    height:auto;
}

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

How can I join elements of an array in Bash?

Here's a single liner that is a bit weird but works well for multi-character delimiters and supports any value (including containing spaces or anything):

ar=(abc "foo bar" 456)
delim=" | "
printf "%s\n$delim\n" "${ar[@]}" | head -n-1 | paste -sd ''

This would show in the console as

abc | foo bar | 456

Note: Notice how some solutions use printf with ${ar[*]} and some with ${ar[@]}?

The ones with @ use the printf feature that supports multiple arguments by repeating the format template.

The ones with * should not be used. They do not actually need printfand rely on manipulating the field separator and bash's word expansion. These would work just as well with echo, cat, etc. - these solutions likely use printf because the author doesn't really understand what they are doing...

How to disable and then enable onclick event on <div> with javascript

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

$("#id").attr('disabled','disabled');

Hope this helps.

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

determine DB2 text string length

From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:

select * from table where length(RTRIM(fieldName))=10

UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:

select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890  ' as varchar(30)) )) 
as tab(fieldName)

FIELDNAME                      LEN_ONLY    LEN_RTRIM
------------------------------ ----------- -----------
1234567890                              12          10

One can test this by using this term:

where length(fieldName)!=length(rtrim(fieldName))

How to include a quote in a raw Python string

Python has more than one way to do strings. The following string syntax would allow you to use double quotes:

'''what"ever'''

JS strings "+" vs concat method

MDN has the following to say about string.concat():

It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons

Also see the link by @Bergi.

How do I print to the debug output window in a Win32 app?

To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.

OutputDebugString prints to the debugger output when running inside the debugger.

How to determine if Javascript array contains an object with an attribute that equals a given value?

You can use includes from the Ramda library:

i.e:

R.includes({ name: 'Fred' }, [{ name: 'Fred' }]); //=> true

Source: https://ramdajs.com/docs/#includes

Getting unix timestamp from Date()

getTime() retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.

How to select from subquery using Laravel Query Builder?

I like doing something like this:

Message::select('*')
->from(DB::raw("( SELECT * FROM `messages`
                  WHERE `to_id` = ".Auth::id()." AND `isseen` = 0
                  GROUP BY `from_id` asc) as `sub`"))
->count();

It's not very elegant, but it's simple.

Trying to merge 2 dataframes but get ValueError

@Arnon Rotem-Gal-Oz answer is right for the most part. But I would like to point out the difference between df['year']=df['year'].astype(int) and df.year.astype(int). df.year.astype(int) returns a view of the dataframe and doesn't not explicitly change the type, atleast in pandas 0.24.2. df['year']=df['year'].astype(int) explicitly change the type because it's an assignment. I would argue that this is the safest way to permanently change the dtype of a column.

Example:

df = pd.DataFrame({'Weed': ['green crack', 'northern lights', 'girl scout cookies'], 'Qty':[10,15,3]}) df.dtypes

Weed object, Qty int64

df['Qty'].astype(str) df.dtypes

Weed object, Qty int64

Even setting the inplace arg to True doesn't help at times. I don't know why this happens though. In most cases inplace=True equals an explicit assignment.

df['Qty'].astype(str, inplace = True) df.dtypes

Weed object, Qty int64

Now the assignment,

df['Qty'] = df['Qty'].astype(str) df.dtypes

Weed object, Qty object

Gitignore not working

Does git reset --hard work for anyone? I am not saying this is a good solution, it just seemed to work first time I tried.

Change background colour for Visual Studio

Tools --> Options --> Environment --> Fonts and Colors

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

How to add to an existing hash in Ruby

You can use double splat operator which is available since Ruby 2.0:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}

Python: What OS am I running on?

If you not looking for the kernel version etc, but looking for the linux distribution you may want to use the following

in python2.6+

>>> import platform
>>> print platform.linux_distribution()
('CentOS Linux', '6.0', 'Final')
>>> print platform.linux_distribution()[0]
CentOS Linux
>>> print platform.linux_distribution()[1]
6.0

in python2.4

>>> import platform
>>> print platform.dist()
('centos', '6.0', 'Final')
>>> print platform.dist()[0]
centos
>>> print platform.dist()[1]
6.0

Obviously, this will work only if you are running this on linux. If you want to have more generic script across platforms, you can mix this with code samples given in other answers.

PHP Get Highest Value from Array

Try using asort().

From documentation:

asort - Sort an array and maintain index association

Description:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Plotting multiple time series on the same plot using ggplot()

If both data frames have the same column names then you should add one data frame inside ggplot() call and also name x and y values inside aes() of ggplot() call. Then add first geom_line() for the first line and add second geom_line() call with data=df2 (where df2 is your second data frame). If you need to have lines in different colors then add color= and name for eahc line inside aes() of each geom_line().

df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))

ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
  geom_line(data=df2,aes(color="Second line"))+
  labs(color="Legend text")

enter image description here

Remove directory which is not empty

Here is an async version of @SharpCoder's answer

const fs = require('fs');
const path = require('path');

function deleteFile(dir, file) {
    return new Promise(function (resolve, reject) {
        var filePath = path.join(dir, file);
        fs.lstat(filePath, function (err, stats) {
            if (err) {
                return reject(err);
            }
            if (stats.isDirectory()) {
                resolve(deleteDirectory(filePath));
            } else {
                fs.unlink(filePath, function (err) {
                    if (err) {
                        return reject(err);
                    }
                    resolve();
                });
            }
        });
    });
};

function deleteDirectory(dir) {
    return new Promise(function (resolve, reject) {
        fs.access(dir, function (err) {
            if (err) {
                return reject(err);
            }
            fs.readdir(dir, function (err, files) {
                if (err) {
                    return reject(err);
                }
                Promise.all(files.map(function (file) {
                    return deleteFile(dir, file);
                })).then(function () {
                    fs.rmdir(dir, function (err) {
                        if (err) {
                            return reject(err);
                        }
                        resolve();
                    });
                }).catch(reject);
            });
        });
    });
};

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

Where is the list of predefined Maven properties

I think the best place to look is the Super POM.

As an example, at the time of writing, the linked reference shows some of the properties between lines 32 - 48.

The interpretation of this is to follow the XPath as a . delimited property.

So, for example:

${project.build.testOutputDirectory} == ${project.build.directory}/test-classes

And:

${project.build.directory} == ${project.basedir}/target

Thus combining them, we find:

${project.build.testOutputDirectory} == ${project.basedir}/target/test-classes

(To reference the resources directory(s), see this stackoverflow question)


<project>
    <modelVersion>4.0.0</modelVersion>
    .
    .
    .
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        .
        .
        .
    </build>
    .
    .
    .
</project>

How to write the code for the back button?

<button onclick="history.go(-1);">Back </button>

Default password of mysql in ubuntu server 16.04

  1. the first you should stop mysql
  2. use this command sudo mysqld_safe --skip-grant-tables --skip-networking &
  3. and then input mysql -u root try this way,I have been solved my problem with this method.

splitting a string based on tab in the file

Split on tab, but then remove all blank matches.

text = "hi\tthere\t\t\tmy main man"
print [splits for splits in text.split("\t") if splits is not ""]

Outputs:

['hi', 'there', 'my main man']

Getting the current date in visual Basic 2008

You may just want:

Dim regDate As Date = Date.Today()

How to get PID of process I've just started within java program?

For GNU/Linux & MacOS (or generally UNIX like) systems, I've used below method which works fine:

private int tryGetPid(Process process)
{
    if (process.getClass().getName().equals("java.lang.UNIXProcess"))
    {
        try
        {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            return f.getInt(process);
        }
        catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e)
        {
        }
    }

    return 0;
}

Is it good practice to make the constructor throw an exception?

I've always considered throwing checked exceptions in the constructor to be bad practice, or at least something that should be avoided.

The reason for this is that you cannot do this :

private SomeObject foo = new SomeObject();

Instead you must do this :

private SomeObject foo;
public MyObject() {
    try {
        foo = new SomeObject()
    } Catch(PointlessCheckedException e) {
       throw new RuntimeException("ahhg",e);
    }
}

At the point when I'm constructing SomeObject I know what it's parameters are so why should I be expected to wrap it in a try catch? Ahh you say but if I'm constructing an object from dynamic parameters I don't know if they're valid or not. Well, you could... validate the parameters before passing them to the constructor. That would be good practice. And if all you're concerned about is whether the parameters are valid then you can use IllegalArgumentException.

So instead of throwing checked exceptions just do

public SomeObject(final String param) {
    if (param==null) throw new NullPointerException("please stop");
    if (param.length()==0) throw new IllegalArgumentException("no really, please stop");
}

Of course there are cases where it might just be reasonable to throw a checked exception

public SomeObject() {
    if (todayIsWednesday) throw new YouKnowYouCannotDoThisOnAWednesday();
}

But how often is that likely?

Javascript: Unicode string to hex

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

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

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

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

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

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


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

how to properly display an iFrame in mobile safari

This only works if you control both the outside page and the iframe page.

On the outside page, make the iframe unscrollable.

<iframe src="" height=200 scrolling=no></iframe>

On the iframe page, add this.

<!doctype html>
...
<style>
html, body {height:100%; overflow:hidden}
body {overflow:auto; -webkit-overflow-scrolling:touch}
</style>

This works because modern browsers uses html to determine the height, so we just give that a fixed height and turn the body into a scrollable node.

Anaconda-Navigator - Ubuntu16.04

Use the following command on your terminal (Ctrl + Alt + T):-

$ conda activate
$ anaconda-navigator

Getting DOM elements by classname

DOMDocument is slow to type and phpQuery has bad memory leak issues. I ended up using:

https://github.com/wasinger/htmlpagedom

To select a class:

include 'includes/simple_html_dom.php';

$doc = str_get_html($html);
$href = $doc->find('.lastPage')[0]->href;

I hope this helps someone else as well

Using headers with the Python requests library's get method

This answer taught me that you can set headers for an entire session:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

Bonus: Sessions also handle cookies.

NoSql vs Relational database

RDBMS focus more on relationship and NoSQL focus more on storage.

You can consider using NoSQL when your RDBMS reaches bottlenecks. NoSQL makes RDBMS more flexible.

html - table row like a link

After reading this thread and some others I came up with the following solution in javascript:

function trs_makelinks(trs) {
    for (var i = 0; i < trs.length; ++i) {
        if (trs[i].getAttribute("href") != undefined) {
            var tr = trs[i];
            tr.onclick = function () { window.location.href = this.getAttribute("href"); };
            tr.onkeydown = function (e) {
                var e = e || window.event;
                if ((e.keyCode === 13) || (e.keyCode === 32)) {
                    e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                    this.click();
                }
            };
            tr.role = "button";
            tr.tabIndex = 0;
            tr.style.cursor = "pointer";
        }
    }
}

/* It could be adapted for other tags */
trs_makelinks(document.getElementsByTagName("tr"));
trs_makelinks(document.getElementsByTagName("td"));
trs_makelinks(document.getElementsByTagName("th"));

To use it put the href in tr/td/th that you desire to be clickable like: <tr href="http://stackoverflow.com">. And make sure the script above is executed after the tr element is created (by its placement or using event handlers).

The downside is it won't totally make the TRs behave as links like with divs with display: table;, and they won't be keyboard-selectable or have status text. Edit: I made keyboard navigation work by setting onkeydown, role and tabIndex, you could remove that part if only mouse is needed. They won't show the URL in statusbar on hovering though.

You can style specifically the link TRs with "tr[href]" CSS selector.

What is a mutex?

Mutual Exclusion. Here's the Wikipedia entry on it.

The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.

Specific details of how this is accomplished obviously varies greatly by programming language.

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2013, I couldn't get "Include in Project" to work when right-clicking on a folder. What did work is expanding the folder, selecting all the files then choosing "Include in Project". It was quite tedious as you have to do each folder one by one (but at least you can do all files in each folder in one go), and it appears to store the file path (you can see this by viewing properties on the file and looking at the "Relative Path" option.)

I am hoping to use this to deploy some data files in a Visual Studio Installer project, and it seems to pick up the included files and preserve their paths.

How to check if a character in a string is a digit or letter

import java.util.*;

public class String_char 
{

    public static void main(String arg[]){   

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the value");
        String data;
        data = in.next();

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            System.out.println("Character");
            }
            else{
                System.out.println("Symbol");
             }
        }
    } 
}

How to see the actual Oracle SQL statement that is being executed

I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file.

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

Runtime.getRuntime().exec(
    new String[]{
        "yourscript.exe", 
        String.valueOf(mypoint.x),
        String.valueOf(mypoint.y)}
);

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here: https://www.autoitscript.com/

Differences between fork and exec

I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()/exec(), especially for someone used to the Windows CreateProcess() model:

A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)

.

In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)

.

It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3 exec System Calls)

Once you understand the distinction between a program and a process, the behavior of fork() and exec() function can be summarized as:

  • fork() creates a duplicate of the current process
  • exec() replaces the program in the current process with another program

(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)

Math operations from string

A simple way but dangerous way to do this would be to use eval(). eval() executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:

import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
  print eval(s)
else:
  print "Try entering a math problem"

Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

MySQL select query with multiple conditions

I would use this query:

SELECT
  user_id
FROM
  wp_usermeta 
WHERE 
  (meta_key = 'first_name' AND meta_value = '$us_name') OR 
  (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') OR 
  (meta_key = 'u_city' AND meta_value = '$us_reg') OR
  (meta_key = 'us_course' AND meta_value = '$us_course')
GROUP BY
  user_id
HAVING
  COUNT(DISTINCT meta_key)=4

this will select all user_id that meets all four conditions.

What is the "double tilde" (~~) operator in JavaScript?

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

For more info, see:

TypeError: unhashable type: 'dict'

A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---

import json

a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]


set(c)
json.dumps(a) in c

Output -

set(['{"a": 10, "b": 20}'])
True

How add unique key to existing table (with non uniques rows)

You can do as yAnTar advised

ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY

OR

You can add a constraint

ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)

But I think to not lose your existing data, you can add an indentity column and then make a composite key.

Convert all first letter to upper case, rest lower for each word

Try this technique; It returns the desired result

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());

And don't forget to use System.Globalization.

How to install and run Typescript locally in npm?

It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script that calls tsc in your package.json file so that you can run:

npm run tsc 

Include -- before you pass in options (or just include them in the script):

npm run tsc -- -v

Here's an example package.json:

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

how to release localhost from Error: listen EADDRINUSE

ps -ef |grep node find app.js , kill pid of app.js

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

Give hibernate.connection.url as "jdbc:oracle:thin:@127.0.0.1:1521:xe" then you can solve above issue. Because oracle's default SID is "xe" so we should give like this. When I gave like this data has been inserted into DB without any SQL exceptions, it's my real time experience.

JavaScript object: access variable property by name as string

ThiefMaster's answer is 100% correct, although I came across a similar problem where I needed to fetch a property from a nested object (object within an object), so as an alternative to his answer, you can create a recursive solution that will allow you to define a nomenclature to grab any property, regardless of depth:

function fetchFromObject(obj, prop) {

    if(typeof obj === 'undefined') {
        return false;
    }

    var _index = prop.indexOf('.')
    if(_index > -1) {
        return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
    }

    return obj[prop];
}

Where your string reference to a given property ressembles property1.property2

Code and comments in JsFiddle.

Android: Getting "Manifest merger failed" error after updating to a new version of gradle

I solve that with putting this at the end of my app module build.gradle:

    configurations.all {
     resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.0'
        }
    }
  }
}

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How do I use the conditional operator (? :) in Ruby?

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

However, in Ruby, if is also an expression so: if a then b else c end === a ? b : c, except for precedence issues. Both are expressions.

Examples:

puts (if 1 then 2 else 3 end) # => 2

puts 1 ? 2 : 3                # => 2

x = if 1 then 2 else 3 end
puts x                        # => 2

Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1 with some extra junk after it), but they are not required in the last case as said issue does not arise.

You can use the "long-if" form for readability on multiple lines:

question = if question.size > 20 then
  question.slice(0, 20) + "..."
else 
  question
end

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

Header and footer in CodeIgniter

Try following

Folder structure

-application
 --controller
   ---dashboards.php
 --views
   ---layouts
      ----application.php
   ---dashboards
      ----index.php

Controller

class Dashboards extends CI_Controller
{

   public function __construct()
   {
     parent::__construct();
     $data                = array();
     $data['js']          = 'dashboards.js'
     $data['css']         = 'dashbaord.css'
   }

   public function index()
   { 
     $data                = array();
     $data['yield']       = 'dashboards/index';

     $this->load->view('layouts/application', $data);
   }
}

View

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" />
      <title>Some Title</title>
      <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/app.css" />
      <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/<?php echo $css; ?>" />
   </head>
   <body>
     <header></header>
     <section id="container" role="main">
     <?php $this->load->view($yield); ?>
     </section>
     <footer></footer>
     <script src="<php echo base_url(); ?>assets/js/app.js"></script>
     <script src="<php echo base_url(); ?>assets/js/<?php echo $js; ?>"></script>
  </body>
</html>

When you need to load different js, css or whatever in the header or footer use the __construct function to $this->load->vars

Kind of a rails like approach here

Handler vs AsyncTask vs Thread

Handler - is communication medium between threads. In android it is mostly used to communicate with main thread by creating and sending messages through handler

AsyncTask - is used to perform long running applications in a background thread. With nAsyncTask you get can do the operation in a background thread and get the result in the main thread of the application.

Thread - is a light weight process, to achieve concurrency and maximum cpu utilization. In android you can use thread to perform activities which does not touch UI of the app

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Basically It is used in HeapOverflows or other reversing type Problems i.e. If you want to change a 64 bit ELF to 32 bit ELF and it is showing error while converting.

You can simply run the commands

apt-get install gcc-multilib g++-multilib

which will update your libraries Packages upgraded:

The following additional packages will be installed: g++-8-multilib gcc-8-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-dev-i386 libc6-dev-x32 libc6-i386 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1 Suggested packages: lib32stdc++6-8-dbg libx32stdc++6-8-dbg glibc-doc The following NEW packages will be installed: g++-8-multilib g++-multilib gcc-8-multilib gcc-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc6-dev-i386 libc6-dev-x32 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1

similar to this will be shown to your terminal

Calculating distance between two points (Latitude, Longitude)

The below function gives distance between two geocoordinates in miles

create function [dbo].[fnCalcDistanceMiles] (@Lat1 decimal(8,4), @Long1 decimal(8,4), @Lat2 decimal(8,4), @Long2 decimal(8,4))
returns decimal (8,4) as
begin
declare @d decimal(28,10)
-- Convert to radians
set @Lat1 = @Lat1 / 57.2958
set @Long1 = @Long1 / 57.2958
set @Lat2 = @Lat2 / 57.2958
set @Long2 = @Long2 / 57.2958
-- Calc distance
set @d = (Sin(@Lat1) * Sin(@Lat2)) + (Cos(@Lat1) * Cos(@Lat2) * Cos(@Long2 - @Long1))
-- Convert to miles
if @d <> 0
begin
set @d = 3958.75 * Atan(Sqrt(1 - power(@d, 2)) / @d);
end
return @d
end 

The below function gives distance between two geocoordinates in kilometres

CREATE FUNCTION dbo.fnCalcDistanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT 
AS
BEGIN

    RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END

The below function gives distance between two geocoordinates in kilometres using Geography data type which was introduced in sql server 2008

DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.STDistance(@h);

Usage:

select [dbo].[fnCalcDistanceKM](13.077085,80.262675,13.065701,80.258916)

Reference: Ref1,Ref2

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

How do I store and retrieve a blob from sqlite?

This worked fine for me (C#):

byte[] iconBytes = null;
using (var dbConnection = new SQLiteConnection(DataSource))
{
    dbConnection.Open();
    using (var transaction = dbConnection.BeginTransaction())
    {
        using (var command = new SQLiteCommand(dbConnection))
        {
            command.CommandText = "SELECT icon FROM my_table";

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"]))
                    {
                        iconBytes = (byte[]) reader["icon"];
                    }
                }
            }
        }
        transaction.Commit();
    }
}

No need for chunking. Just cast to a byte array.

Is there a printf converter to print in binary format?

No standard and portable way.

Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.

Confirmation before closing of tab/browser

Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

how to define variable in jquery

In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

Maven Installation OSX Error Unsupported major.minor version 51.0

I solved it putting a old version of maven (2.x), using brew:

brew uninstall maven
brew tap homebrew/versions 
brew install maven2

C# string replace

The simplest way is to do

line.Replace(@",", @";");

Output is shown as below:

enter image description here

Stop setInterval call in JavaScript

I guess the following code will help:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);

You did the code 100% correct... So... What's the problem? Or it's a tutorial...

How can I read numeric strings in Excel cells as string (not numbers)?

As already mentioned in the Poi's JavaDocs (https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29) don't use:

cell.setCellType(Cell.CELL_TYPE_STRING);

but use:

DataFormatter df = new DataFormatter();
String value = df.formatCellValue(cell);

More examples on http://massapi.com/class/da/DataFormatter.html

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

The Use of Multiple JFrames: Good or Bad Practice?

It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.

Getting the thread ID from a thread

GetThreadId returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.

GetCurrentThreadId returns the ID of the current thread.

GetCurrentThreadId has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId property.

Android: how to handle button click

To make things easier asp Question 2 stated, you can make use of lambda method like this to save variable memory and to avoid navigating up and down in your view class

//method 1
findViewById(R.id.buttonSend).setOnClickListener(v -> {
          // handle click
});

but if you wish to apply click event to your button at once in a method.

you can make use of Question 3 by @D. Tran answer. But do not forget to implement your view class with View.OnClickListener.

In other to use Question #3 properly

How to get file name from file path in android

you can use the Common IO library which can get you the Base name of your file and the Extension.

 String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
      String fileName=FilenameUtils.getBaseName(fileUrl);
           String    fileExtention=FilenameUtils.getExtension(fileUrl);
//this will return filename:1414240995236 and fileExtention:jpg

Is there any use for unique_ptr with array?

Contrary to std::vector and std::array, std::unique_ptr can own a NULL pointer.
This comes in handy when working with C APIs that expect either an array or NULL:

void legacy_func(const int *array_or_null);

void some_func() {    
    std::unique_ptr<int[]> ptr;
    if (some_condition) {
        ptr.reset(new int[10]);
    }

    legacy_func(ptr.get());
}

Restoring MySQL database from physical files

I once copied these files to the database storage folder for a mysql database which was working, started the db and waited for it to "repair" the files, then extracted them with mysqldump.

jQuery scroll() detect when user stops scrolling

Rob W suggected I check out another post here on stack that was essentially a similar post to my original one. Which reading through that I found a link to a site:

http://james.padolsey.com/javascript/special-scroll-events-for-jquery/

This actually ended up helping solve my problem very nicely after a little tweaking for my own needs, but over all helped get a lot of the guff out of the way and saved me about 4 hours of figuring it out on my own.

Seeing as this post seems to have some merit, I figured I would come back and provide the code found originally on the link mentioned, just in case the author ever decided to go a different direction with the site and ended up taking down the link.

(function(){

    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    special.scrollstart = {
        setup: function() {

            var timer,
                handler =  function(evt) {

                    var _self = this,
                        _args = arguments;

                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        jQuery.event.handle.apply(_self, _args);
                    }

                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);

                };

            jQuery(this).bind('scroll', handler).data(uid1, handler);

        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };

    special.scrollstop = {
        latency: 300,
        setup: function() {

            var timer,
                    handler = function(evt) {

                    var _self = this,
                        _args = arguments;

                    if (timer) {
                        clearTimeout(timer);
                    }

                    timer = setTimeout( function(){

                        timer = null;
                        evt.type = 'scrollstop';
                        jQuery.event.handle.apply(_self, _args);

                    }, special.scrollstop.latency);

                };

            jQuery(this).bind('scroll', handler).data(uid2, handler);

        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };

})();

How to find patterns across multiple lines using grep?

This can be done easily by first using tr to replace the newlines with some other character:

tr '\n' '\a' | grep -o 'abc.*def' | tr '\a' '\n'

Here, I am using the alarm character, \a (ASCII 7) in place of a newline. This is almost never found in your text, and grep can match it with a ., or match it specifically with \a.

object==null or null==object?

This trick supposed to prevent v = null kind of typos.

But Java allows only boolean expressions as if() conditions so that trick does not make much sense, compiler will find those typos anyway.

It is still valuable trick for C/C++ code though.

JMS Topic vs Queues

That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.

Show only two digit after decimal

i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##"); 
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));

How to properly use jsPDF library

This is finally what did it for me (and triggers a disposition):

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

What is the Maximum Size that an Array can hold?

System.Int32.MaxValue

Assuming you mean System.Array, ie. any normally defined array (int[], etc). This is the maximum number of values the array can hold. The size of each value is only limited by the amount of memory or virtual memory available to hold them.

This limit is enforced because System.Array uses an Int32 as it's indexer, hence only valid values for an Int32 can be used. On top of this, only positive values (ie, >= 0) may be used. This means the absolute maximum upper bound on the size of an array is the absolute maximum upper bound on values for an Int32, which is available in Int32.MaxValue and is equivalent to 2^31, or roughly 2 billion.

On a completely different note, if you're worrying about this, it's likely you're using alot of data, either correctly or incorrectly. In this case, I'd look into using a List<T> instead of an array, so that you are only using as much memory as needed. Infact, I'd recommend using a List<T> or another of the generic collection types all the time. This means that only as much memory as you are actually using will be allocated, but you can use it like you would a normal array.

The other collection of note is Dictionary<int, T> which you can use like a normal array too, but will only be populated sparsely. For instance, in the following code, only one element will be created, instead of the 1000 that an array would create:

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[1000] = "Hello world!";
Console.WriteLine(foo[1000]);

Using Dictionary also lets you control the type of the indexer, and allows you to use negative values. For the absolute maximal sized sparse array you could use a Dictionary<ulong, T>, which will provide more potential elements than you could possible think about.

jQuery checkbox check/uncheck

Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

What is Hash and Range Primary Key?

A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.

In a simple words range + hash key = composite primary key CoreComponents of Dynamodb enter image description here

A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.

So both have a different purpose and together help to do complex query. In the above example hashkey1 can have multiple n-range. Another example of range and hashkey is game, userA(hashkey) can play Ngame(range)

enter image description here

The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.

A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.

enter image description here

https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html

MySQL timestamp select date range

I can see people giving lots of comments on this question. But I think, simple use of LIKE could be easier to get the data from the table.

SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'

Use LIKE and post data wild character search. Hopefully this will solve your problem.

Failed to load ApplicationContext for JUnit test of Spring controller

If you are using Maven, add the below config in your pom.xml:

<build>
    <testResources>
                <testResource>
                    <directory>src/main/webapp</directory>
                </testResource>
    </testResources>
</build>

With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.

Table variable error: Must declare the scalar variable "@temp"

try the following query:

SELECT ID,
   Name
INTO #tempTable
FROM Table

SELECT *
FROM #tempTable
WHERE ID = 1

It doesn't need to declare table.

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I ran into this issue due to a silly mistake. Make sure the date actually exists!

For example:

September 31, 2015 does not exist.

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931'

So this fails with the message:

Error converting data type varchar to datetime.

To fix it, input a valid date:

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930'

And it executes just fine.

React Router v4 - How to get current route?

Here is a solution using history Read more

import { createBrowserHistory } from "history";

const history = createBrowserHistory()

inside Router

<Router>
   {history.location.pathname}
</Router>

How do you return the column names of a table?

USE[Database] SELECT TABLE_NAME,TABLE_SCHEMA,[Column_Name],[Data_type] FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='dbo'

How do I find duplicates across multiple columns?

Given a staging table with 70 columns and only 4 representing duplicates, this code will return the offending columns:

SELECT 
    COUNT(*)
    ,LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
FROM Staging.dbo.Stage S
GROUP BY 
    LTRIM(RTRIM(S.TransactionDate)) 
    ,LTRIM(RTRIM(S.TransactionTime))
    ,LTRIM(RTRIM(S.TransactionTicketNumber)) 
    ,LTRIM(RTRIM(GrossCost)) 
HAVING COUNT(*) > 1

.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

Deleting rows from parent and child tables

Two possible approaches.

  1. If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.

  2. Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?

      delete from child_table
          where parent_id in (
               select parent_id from parent_table
                    where updd_tms != (sysdate-30)
    

    -- now delete the parent table records

    delete from parent_table
    where updd_tms != (sysdate-30);
    

---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
    for v_rec in (select parent_id, child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation, 
    -- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.