Programs & Examples On #Decouple

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Change to root build.gradle file

to

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

MVC: How to Return a String as JSON

Use the following code in your controller:

return Json(new { success = string }, JsonRequestBehavior.AllowGet);

and in JavaScript:

success: function (data) {
    var response = data.success;
    ....
}

Flash CS4 refuses to let go

Also, to use your new namespaced class you can also do

var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()

URL to load resources from the classpath in Java

You can also set the property programmatically during startup:

final String key = "java.protocol.handler.pkgs";
String newValue = "org.my.protocols";
if (System.getProperty(key) != null) {
    final String previousValue = System.getProperty(key);
    newValue += "|" + previousValue;
}
System.setProperty(key, newValue);

Using this class:

package org.my.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(final URL u) throws IOException {
        final URL resourceUrl = ClassLoader.getSystemClassLoader().getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Thus you get the least intrusive way to do this. :) java.net.URL will always use the current value from the system properties.

Variable used in lambda expression should be final or effectively final

A variable used in lambda expression should be a final or effectively final, but you can assign a value to a final one element array.

private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) {
    try {
        TimeZone calTzLocal[] = new TimeZone[1];
        calTzLocal[0] = calTz;
        cal.getComponents().get("VTIMEZONE").forEach(component -> {
            TimeZone v = component;
            v.getTimeZoneId();
            if (calTzLocal[0] == null) {
                calTzLocal[0] = TimeZone.getTimeZone(v.getTimeZoneId().getValue());
            }
        });
    } catch (Exception e) {
        log.warn("Unable to determine ical timezone", e);
    }
    return null;
}

R memory management / cannot allocate vector of size n Mb

Here is a presentation on this topic that you might find interesting:

http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/

I haven't tried the discussed things myself, but the bigmemory package seems very useful

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

SVN: Folder already under version control but not comitting?

For me doing a svn update, followed by svn commit worked. There were no .svn folders present in folder which was failing to add.

How can I get the name of an object in Python?

Here's another way to think about it. Suppose there were a name() function that returned the name of its argument. Given the following code:

def f(a):
    return a

b = "x"
c = b
d = f(c)

e = [f(b), f(c), f(d)]

What should name(e[2]) return, and why?

Converting Float to Dollars and Cents

In python 3, you can use:

import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )

Output

'$1,234.50'

Batch file. Delete all files and folders in a directory

Use:

  • Create a batch file

  • Copy the below text into the batch file

    set folder="C:\test"
    cd /d %folder%
    for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
    

It will delete all files and folders.

How to generate unique ID with node.js

used https://www.npmjs.com/package/uniqid in npm

npm i uniqid

It will always create unique id's based on the current time, process and machine name.

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

Features:-

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

How to remove new line characters from data rows in mysql?

1) Replace all new line and tab characters with spaces.

2) Remove all leading and trailing spaces.

 UPDATE mytable SET `title` = TRIM(REPLACE(REPLACE(REPLACE(`title`, '\n', ' '), '\r', ' '), '\t', ' '));

Django Rest Framework File Upload

I'd like to write another option that I feel is cleaner and easier to maintain. We'll be using the defaultRouter to add CRUD urls for our viewset and we'll add one more fixed url specifying the uploader view within the same viewset.

**** views.py 

from rest_framework import viewsets, serializers
from rest_framework.decorators import action, parser_classes
from rest_framework.parsers import JSONParser, MultiPartParser
from rest_framework.response import Response
from rest_framework_csv.parsers import CSVParser
from posts.models import Post
from posts.serializers import PostSerializer     


class PostsViewSet(viewsets.ModelViewSet):

    queryset = Post.objects.all()
    serializer_class = PostSerializer 
    parser_classes = (JSONParser, MultiPartParser, CSVParser)


    @action(detail=False, methods=['put'], name='Uploader View', parser_classes=[CSVParser],)
    def uploader(self, request, filename, format=None):
        # Parsed data will be returned within the request object by accessing 'data' attr  
        _data = request.data

        return Response(status=204)

Project's main urls.py

**** urls.py 

from rest_framework import routers
from posts.views import PostsViewSet


router = routers.DefaultRouter()
router.register(r'posts', PostsViewSet)

urlpatterns = [
    url(r'^posts/uploader/(?P<filename>[^/]+)$', PostsViewSet.as_view({'put': 'uploader'}), name='posts_uploader')
    url(r'^', include(router.urls), name='root-api'),
    url('admin/', admin.site.urls),
]

.- README.

The magic happens when we add @action decorator to our class method 'uploader'. By specifying "methods=['put']" argument, we are only allowing PUT requests; perfect for file uploading.

I also added the argument "parser_classes" to show you can select the parser that will parse your content. I added CSVParser from the rest_framework_csv package, to demonstrate how we can accept only certain type of files if this functionality is required, in my case I'm only accepting "Content-Type: text/csv". Note: If you're adding custom Parsers, you'll need to specify them in parsers_classes in the ViewSet due the request will compare the allowed media_type with main (class) parsers before accessing the uploader method parsers.

Now we need to tell Django how to go to this method and where can be implemented in our urls. That's when we add the fixed url (Simple purposes). This Url will take a "filename" argument that will be passed in the method later on. We need to pass this method "uploader", specifying the http protocol ('PUT') in a list to the PostsViewSet.as_view method.

When we land in the following url

 http://example.com/posts/uploader/ 

it will expect a PUT request with headers specifying "Content-Type" and Content-Disposition: attachment; filename="something.csv".

curl -v -u user:pass http://example.com/posts/uploader/ --upload-file ./something.csv --header "Content-type:text/csv"

No Android SDK found - Android Studio

Here is the solution just copy your SDK Manager.exe file at the root folder of your android studio's installation, Sync your project and cheers... here is the link for details. running Android Studio on Windows 7 fails, no Android SDK found

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

How to refresh Android listview?

i got some problems with dynamic refresh of my listview.

Call notifyDataSetChanged() on your Adapter.

Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.

notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.

In my second class i used

Runnable run = new Runnable(){
     public void run(){
         contactsActivity.update();
     }
};
contactsActivity.runOnUiThread(run);

to acces the update() from my Activity. This update includes

myAdapter.notifyDataSetChanged();

to tell the Adapter to refresh the view. Worked fine as far as I can say.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

You May Write this below code insdie your current java programme

System.setProperty("https.protocols", "TLSv1.1");

or

System.setProperty("http.proxyHost", "proxy.com");

System.setProperty("http.proxyPort", "911");

omp parallel vs. omp parallel for

Although both versions of the specific example are equivalent, as already mentioned in the other answers, there is still one small difference between them. The first version includes an unnecessary implicit barrier, encountered at the end of the "omp for". The other implicit barrier can be found at the end of the parallel region. Adding "nowait" to "omp for" would make the two codes equivalent, at least from an OpenMP perspective. I mention this because an OpenMP compiler could generate slightly different code for the two cases.

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Just to point out that cordova brings in it's own npm with the graceful-fs dependency, so if you use Cordova make sure that it is the latest so you get the latest graceful-fs from that as well.

How to check if the URL contains a given string?

You would use indexOf like this:

if(window.location.href.indexOf("franky") != -1){....}

Also notice the addition of href for the string otherwise you would do:

if(window.location.toString().indexOf("franky") != -1){....}

Is it possible to set a custom font for entire of application?

Since the release of Android Oreo and its support library (26.0.0) you can do this easily. Refer to this answer in another question.

Basically your final style will look like this:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="fontFamily">@font/your_font</item> <!-- target android sdk versions < 26 and > 14 -->
</style>

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

A JOIN With Additional Conditions Using Query Builder or Eloquent

The sql query sample like this

LEFT JOIN bookings  
    ON rooms.id = bookings.room_type_id
    AND (bookings.arrival = ?
        OR bookings.departure = ?)

Laravel join with multiple conditions

->leftJoin('bookings', function($join) use ($param1, $param2) {
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($param1, $param2) {
        $query->on('bookings.arrival', '=', $param1);
        $query->orOn('departure', '=',$param2);
    });
})

Java Compare Two List's object values?

Using java 8 removeIf to compare similar items

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}

Is the buildSessionFactory() Configuration method deprecated in Hibernate

In Hibernate 4.2.2

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Test {
    public static void main(String[] args) throws Exception
{
    Configuration configuration = new Configuration()
            .configure();

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()).buildServiceRegistry();

    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    Users users = new Users();

    ... ...

    session.save(users);

    transaction.commit();

    session.close();

    sessionFactory.close();

    }
}

How do I get console input in javascript?

Good old readline();.

See MDN (archive).

Bootstrap 4 Center Vertical and Horizontal Alignment

From the doc (bootsrap 4):

https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I was also facing the error "Error preloading the connection pool" while using Oracle 10g Express Edition with my Spring and CAS based application during login.

My CAS based application only has classes12.jar in its classpath, Placing ojdbc14.jar in the classpath has resolved my problem.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

try to change the compileSdkVersion to: compileSdkVersion 28

ngOnInit not being called when Injectable class is Instantiated

Adding to answer by @Sasxa,

In Injectables you can use class normally that is putting initial code in constructor instead of using ngOnInit(), it works fine.

what are the .map files used for in Bootstrap 3.x?

Map files (source maps) are there to de-reference minified code (css and javascript).

And they are mainly used to help developers debugging a production environment, because developers usually use minified files for production which makes it impossible to debug. Map files help them de-referencing the code to see how the original file looked like.

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

How to apply bold text style for an entire row using Apache POI?

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @test nvarchar(100)

SET @test = 'Foreign Tax Credit - 1997'

SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
    right(@test, len(@test) - charindex('-', @test) - 1)  AS RightString

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

What is the best way to update the entity in JPA

Using executeUpdate() on the Query API is faster because it bypasses the persistent context .However , by-passing persistent context would cause the state of instance in the memory and the actual values of that record in the DB are not synchronized.

Consider the following example :

 Employee employee= (Employee)entityManager.find(Employee.class , 1);
 entityManager
     .createQuery("update Employee set name = \'xxxx\' where id=1")
     .executeUpdate();

After flushing, the name in the DB is updated to the new value but the employee instance in the memory still keeps the original value .You have to call entityManager.refresh(employee) to reload the updated name from the DB to the employee instance.It sounds strange if your codes still have to manipulate the employee instance after flushing but you forget to refresh() the employee instance as the employee instance still contains the original values.

Normally , executeUpdate() is used in the bulk update process as it is faster due to bypassing the persistent context

The right way to update an entity is that you just set the properties you want to updated through the setters and let the JPA to generate the update SQL for you during flushing instead of writing it manually.

   Employee employee= (Employee)entityManager.find(Employee.class ,1);
   employee.setName("Updated Name");

How to make padding:auto work in CSS?

You can reset the padding (and I think everything else) with initial to the default.

p {
    padding: initial;
}

convert UIImage to NSData

Create the reference of image....

UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];

displaying image in image view... imagedisplay is reference of imageview:

imagedisplay.image = rainyImage;

convert it into NSData by passing UIImage reference and provide compression quality in float values:

NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);

Convert string to ASCII value python

you can actually do it with numpy:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

How to check if String value is Boolean type in Java?

Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.

Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?

I think Boolean.valueOf() is your friend, javadoc says:

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h"
#include "Ball.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

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();

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

Using textures in THREE.js

In version r82 of Three.js TextureLoader is the object to use for loading a texture.

Loading one texture (source code, demo)

Extract (test.js):

var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
  0.1, 50);

var renderer = ...

[...]

/**
 * Will be called when load completes.
 * The argument will be the loaded texture.
 */
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(20, 20, 20);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var mesh = new THREE.Mesh(objGeometry, objMaterial);

  scene.add(mesh);

  var render = function () {
    requestAnimationFrame(render);

    mesh.rotation.x += 0.010;
    mesh.rotation.y += 0.010;

    renderer.render(scene, camera);
  };

  render();
}

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (xhr) {
  console.log('An error happened');
};

var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);

Loading multiple textures (source code, demo)

In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.

Extract (Globe.js):

Create a new container using Object3D for having two meshes in the same container:

var Globe = function (radius, segments) {

  THREE.Object3D.call(this);

  this.name = "Globe";

  var that = this;

  // instantiate a loader
  var loader = new THREE.TextureLoader();

A map called textures where every object contains the url of a texture file and val for storing the value of a Three.js texture object.

  // earth textures
  var textures = {
    'map': {
      url: 'relief.jpg',
      val: undefined
    },
    'bumpMap': {
      url: 'elev_bump_4k.jpg',
      val: undefined
    },
    'specularMap': {
      url: 'wateretopo.png',
      val: undefined
    }
  };

The array of promises, for each object in the map called textures push a new Promise in the array texturePromises, every Promise will call loader.load. If the value of entry.val is a valid THREE.Texture object, then resolve the promise.

  var texturePromises = [], path = './';

  for (var key in textures) {
    texturePromises.push(new Promise((resolve, reject) => {
      var entry = textures[key]
      var url = path + entry.url

      loader.load(url,
        texture => {
          entry.val = texture;
          if (entry.val instanceof THREE.Texture) resolve(entry);
        },
        xhr => {
          console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
            '% loaded');
        },
        xhr => {
          reject(new Error(xhr +
            'An error occurred loading while loading: ' +
            entry.url));
        }
      );
    }));
  }

Promise.all takes the promise array texturePromises as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.

  // load the geometry and the textures
  Promise.all(texturePromises).then(loadedTextures => {

    var geometry = new THREE.SphereGeometry(radius, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: textures.map.val,
      bumpMap: textures.bumpMap.val,
      bumpScale: 0.005,
      specularMap: textures.specularMap.val,
      specular: new THREE.Color('grey')
    });

    var earth = that.earth = new THREE.Mesh(geometry, material);
    that.add(earth);
  });

For the cloud sphere only one texture is necessary:

  // clouds
  loader.load('n_amer_clouds.png', map => {
    var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: map,
      transparent: true
    });

    var clouds = that.clouds = new THREE.Mesh(geometry, material);
    that.add(clouds);
  });
}

Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;

JavaScript: How do I print a message to the error console?

To actually answer the question:

console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);

Instead of error, you can also use info, log or warn.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

What are non-recursive mutexes good for?

They are absolutely good when you have to make sure the mutex is unlocked before doing something. This is because pthread_mutex_unlock can guarantee that the mutex is unlocked only if it is non-recursive.

pthread_mutex_t      g_mutex;

void foo()
{
    pthread_mutex_lock(&g_mutex);
    // Do something.
    pthread_mutex_unlock(&g_mutex);

    bar();
}

If g_mutex is non-recursive, the code above is guaranteed to call bar() with the mutex unlocked.

Thus eliminating the possibility of a deadlock in case bar() happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.

If g_mutex was recursive, there would be simply no way to make sure it is unlocked before making a call.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

ValueError: unsupported format character while forming strings

I was using python interpolation and forgot the ending s character:

a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s

Watch those typos.

What does if __name__ == "__main__": do?

Every module in python has a attribute called __name__. The value of __name__ attribute is __main__ when the module is run directly, like python my_module.py. Otherwise (like when you say import my_module) the value of __name__ is the name of the module.

Small example to explain in short.

#Script test.py

apple = 42

def hello_world():
    print("I am inside hello_world")

if __name__ == "__main__":
    print("Value of __name__ is: ", __name__)
    print("Going to call hello_world")
    hello_world()

We can execute this directly as

python test.py  

Output

Value of __name__ is: __main__
Going to call hello_world
I am inside hello_world

Now suppose we call above script from other script

#script external_calling.py

import test
print(test.apple)
test.hello_world()

print(test.__name__)

When you execute this

python external_calling.py

Output

42
I am inside hello_world
test

So, above is self explanatory that when you call test from other script, if loop __name__ in test.py will not execute.

C# int to byte[]

byte[] Take_Byte_Arr_From_Int(Int64 Source_Num)
{
   Int64 Int64_Num = Source_Num;
   byte Byte_Num;
   byte[] Byte_Arr = new byte[8];
   for (int i = 0; i < 8; i++)
   {
      if (Source_Num > 255)
      {
         Int64_Num = Source_Num / 256;
         Byte_Num = (byte)(Source_Num - Int64_Num * 256);
      }
      else
      {
         Byte_Num = (byte)Int64_Num;
         Int64_Num = 0;
      }
      Byte_Arr[i] = Byte_Num;
      Source_Num = Int64_Num;
   }
   return (Byte_Arr);
}

Comparing arrays in C#

SequenceEqual can be faster. Namely in the case where almost all of the time, both arrays have indeed the same length and are not the same object.

It's still not the same functionality as the OP's function, as it won't silently compare null values.

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

wait() or sleep() function in jquery?

Realize that this is an old question, but I wrote a plugin to address this issue that someone might find useful.

https://github.com/madbook/jquery.wait

lets you do this:

$('#myElement').addClass('load').wait(2000).addClass('done');

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

Difference between Spring MVC and Spring Boot

SpringBoot is actually pre configured that reduced boiler configuration and providing easiest or quick way to start your application.

SpringBoot take the headache of configuration from developer to it's own self rather than Spring.

Implicitly SpringBoot is based on Spring framework concept like bean, controller , services, jpa etc.

You can say that SpringBoot is a wrapper of Spring.

In SpringBoot by default port of Server is 8080 but if you want to change then go to your application.properties and write

server.port = 8084

How can I use JQuery to post JSON data?

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

What is the difference between Serializable and Externalizable in Java?

To add to the other answers, by implementating java.io.Serializable, you get "automatic" serialization capability for objects of your class. No need to implement any other logic, it'll just work. The Java runtime will use reflection to figure out how to marshal and unmarshal your objects.

In earlier version of Java, reflection was very slow, and so serializaing large object graphs (e.g. in client-server RMI applications) was a bit of a performance problem. To handle this situation, the java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class). This gives you the means to get around the reflection performance bottleneck.

In recent versions of Java (1.3 onwards, certainly) the performance of reflection is vastly better than it used to be, and so this is much less of a problem. I suspect you'd be hard-pressed to get a meaningful benefit from Externalizable with a modern JVM.

Also, the built-in Java serialization mechanism isn't the only one, you can get third-party replacements, such as JBoss Serialization, which is considerably quicker, and is a drop-in replacement for the default.

A big downside of Externalizable is that you have to maintain this logic yourself - if you add, remove or change a field in your class, you have to change your writeExternal/readExternal methods to account for it.

In summary, Externalizable is a relic of the Java 1.1 days. There's really no need for it any more.

BLOB to String, SQL Server

CREATE OR REPLACE FUNCTION HASTANE.getXXXXX(p_rowid in rowid) return VARCHAR2
  as
          l_data long;
  begin
         select XXXXXX into l_data from XXXXX where rowid = p_rowid;
         return substr( l_data, 1, 4000);
  end getlabrapor1;

How do I "Add Existing Item" an entire directory structure in Visual Studio?

The cleanest way that I've found to do this is to create a new Class Library project in the target folder, and redirect all of its build output elsewhere. It still leaves a .csproj file sitting in that folder, but it does let you see it in Visual Studio and pick which files to include in your project.

Docker - Container is not running

docker run -it <image_id> /bin/bash

Run in interactive mode executing then bash shell

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Remove HTML tags from a String

On Android, try this:

String result = Html.fromHtml(html).toString();

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

Example of accessing:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

Django development IDE

Editra supports Django Template Language syntax highlighting. You can configure it either as a better Notepad or a basic IDE.

How to access site running apache server over lan without internet connection

In your httpd.conf make sure you have:

Listen *:80

And if you are using VirtualHosts then set them as given below:

NameVirtualHost *
<VirtualHost *>
   ...
</VirtualHost>

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Initially I also had problem getting FLAG_ACTIVITY_CLEAR_TOP to work. Eventually I got it to work by using the value of it (0x04000000). So looks like there's an Eclipse/compiler issue. But unfortunately the surviving activity is restarted, which is not what I want. So looks like there's no easy solution.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

How to update fields in a model without creating a new record in django?

In my scenario, I want to update the status of status based on his id

student_obj = StudentStatus.objects.get(student_id=101)
student_obj.status= 'Enrolled'
student_obj.save()

Or If you want the last id from Student_Info table you can use the following.

student_obj = StudentStatus.objects.get(student_id=StudentInfo.objects.last().id)
student_obj.status= 'Enrolled'
student_obj.save()

jquery change button color onclick

$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

Use class, Demo:- http://jsfiddle.net/BX6Df/

   $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

if you want to toggle the color each click, you can try this:- http://jsfiddle.net/SMNks/

$('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});


.red
{
    background-color:red;
}

Updated answer for your comment.

http://jsfiddle.net/H2Xhw/

$('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

Launching Google Maps Directions via an intent on Android

Using the latest cross-platform Google Maps URLs: Even if google maps app is missing it will open in browser

Example https://www.google.com/maps/dir/?api=1&origin=81.23444,67.0000&destination=80.252059,13.060604

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.google.com")
    .appendPath("maps")
    .appendPath("dir")
    .appendPath("")
    .appendQueryParameter("api", "1")
    .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

Build .NET Core console application to output an EXE

For debugging purposes, you can use the DLL file. You can run it using dotnet ConsoleApp2.dll. If you want to generate an EXE file, you have to generate a self-contained application.

To generate a self-contained application (EXE in Windows), you must specify the target runtime (which is specific to the operating system you target).

Pre-.NET Core 2.0 only: First, add the runtime identifier of the target runtimes in the .csproj file (list of supported RIDs):

<PropertyGroup>
    <RuntimeIdentifiers>win10-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</PropertyGroup>

The above step is no longer required starting with .NET Core 2.0.

Then, set the desired runtime when you publish your application:

dotnet publish -c Release -r win10-x64
dotnet publish -c Release -r ubuntu.16.10-x64

How to get an MD5 checksum in PowerShell

As stated in the accepted answer, Get-FileHash is easy to use with files, but it is also possible to use it with strings:

$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))

How to hide Soft Keyboard when activity starts

If you don't want to use xml, make a Kotlin Extension to hide keyboard

// In onResume, call this
myView.hideKeyboard()

fun View.hideKeyboard() {
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

Alternatives based on use case:

fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

fun Activity.hideKeyboard() {
    // Calls Context.hideKeyboard
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    view.hideKeyboard()
}

How to show soft keyboard

fun Context.showKeyboard() { // Or View.showKeyboard()
    val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}

Simpler method when simultaneously requesting focus on an edittext

myEdittext.focus()

fun View.focus() {
    requestFocus()
    showKeyboard()
}

Bonus simplification:

Remove requirement for ever using getSystemService: Splitties Library

// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)

How can foreign key constraints be temporarily disabled using T-SQL?

The SQL-92 standard allows for a constaint to be declared as DEFERRABLE so that it can be deferred (implicitly or explicitly) within the scope of a transaction. Sadly, SQL Server is still missing this SQL-92 functionality.

For me, changing a constraint to NOCHECK is akin to changing the database structure on the fly -- dropping constraints certainly is -- and something to be avoided (e.g. users require increased privileges).

HTML/Javascript change div content

you can use following helper function:

function content(divSelector, value) {
    document.querySelector(divSelector).innerHTML = value;
}

content('#content',"whatever");

Where #content must be valid CSS selector

Here is working example.


Additionaly - today (2018.07.01) I made speed comparison for jquery and pure js solutions ( MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

document.getElementById("content").innerHTML = "whatever"; // pure JS
$('#content').html('whatever');                            // jQuery

enter image description here

The jquery solution was slower than pure js solution: 69% on firefox, 61% on safari, 56% on chrome. The fastest browser for pure js was firefox with 560M operations per second, the second was safari 426M, and slowest was chrome 122M.

So the winners are pure js and firefox (3x faster than chrome!)

You can test it in your machine: https://jsperf.com/js-jquery-html-content-change

What is the shortcut in IntelliJ IDEA to find method / functions?

Ctrl + Shift + Alt+ 7 after selecting the method

React native ERROR Packager can't listen on port 8081

Ubuntu/Unix && MacOS

My Metro Bundler was stuck and there were lots of node processes running but I didn't have any other development going on besides react-native, so I ran:

$ killall -9 node

The Metro Bundler is running through node on port 8081 by default, and it can encounter issues sometimes whereby it gets stuck (usually due to pressing CTRL+S in rapid succession with hot reloading on). If you press CTRL+C to kill the react-native run-android process, you will suddenly have a bad time because react-native-run-android will get stuck on :

Scanning folders for symlinks in /home/poop/dev/some-app/node_modules (41ms)

Fix:

$ killall -9 node

$ react-native run-android

Note: if you are developing other apps at the time, killing all the node proceses may interrupt them or any node-based services you have running, so be mindful of the sweeping nature of killall -9. If you aren't running a node-based database or app or you don't mind manually restarting them, then you should be good to go.

The reason I leave this detailed answer on this semi-unrelated question is that mine is a solution to a common semi-related problem that sadly requires 2 steps to fix but luckily only takes 2 steps get back to work.

If you want to surgically remove exactly the Metro Bundler garbage on port 8081, do the steps in the answer from RC_02, which are:

$ sudo lsof -i :8081

$ kill -9 23583

(where 23583 is the process ID)

Accessing MP3 metadata with Python

I looked the above answers and found out that they are not good for my project because of licensing problems with GPL.

And I found out this: PyID3Lib, while that particular python binding release date is old, it uses the ID3Lib, which itself is up to date.

Notable to mention is that both are LGPL, and are good to go.

How to debug Javascript with IE 8

I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

myLog = function() {

    var _div = null;

    this.toJson = function(obj) {

        if (typeof window.uneval == 'function') { return uneval(obj); }
        if (typeof obj == 'object') {
            if (!obj) { return 'null'; }
            var list = [];
            if (obj instanceof Array) {
                    for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                    return '[' + list.join(',') + ']';
            } else {
                    for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                    return '{' + list.join(',') + '}';
            }
        } else if (typeof obj == 'string') {
            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
        } else {
            return new String(obj);
        }

    };

    this.createDiv = function() {

        myLog._div = document.body.appendChild(document.createElement('div'));

        var props = {
            position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
            color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
            fontSize: '11px', whiteSpace: 'nowrap'
        }

        for (var key in props) { myLog._div.style[key] = props[key]; }

    };


    if (!myLog._div) { this.createDiv(); }

    var logEntry = document.createElement('span');

    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
    }

    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);

    // Scroll automatically to the bottom
    myLog._div.scrollTop = myLog._div.scrollHeight;

}

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

Spring Bean Scopes

About prototype bean(s) :

The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

ref : https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html#beans-factory-scopes-prototype

How do you access the value of an SQL count () query in a Java program

        <%
        try{
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
            if(con == null) System.out.print("not connected");
            Statement st = con.createStatement();
            String myStatement = "select count(*) as total from locations";
            ResultSet rs = st.executeQuery(myStatement);
            int num = 0;
            while(rs.next()){
                num = (rs.getInt(1));
            }

        }
        catch(Exception e){
            System.out.println(e);  
        }

        %>

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

PHP - how to create a newline character?

I have also tried this combination within both the single quotes and double quotes. But none has worked. Instead of using \n better use <br/> in the double quotes. Like this..

$variable = "and";
echo "part 1 $variable part 2<br/>";
echo "part 1 ".$variable." part 2";

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

The following worked for me: https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019 I fix it by doing something like this:

const Component = (isFoo ? FooComponent : BarComponent) as React.ElementType

Check folder size in Bash

To just get the size of the directory, nothing more:

du --max-depth=0 ./directory

output looks like

5234232       ./directory

Break string into list of characters in Python

Strings are iterable (just like a list).

I'm interpreting that you really want something like:

fd = open(filename,'rU')
chars = []
for line in fd:
   for c in line:
       chars.append(c)

or

fd = open(filename, 'rU')
chars = []
for line in fd:
    chars.extend(line)

or

chars = []
with open(filename, 'rU') as fd:
    map(chars.extend, fd)

chars would contain all of the characters in the file.

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

How can I search sub-folders using glob.glob module?

You can use Formic with Python 2.6

import formic
fileset = formic.FileSet(include="**/*.txt", directory="C:/Users/sam/Desktop/")

Disclosure - I am the author of this package.

WAMP Cannot access on local network 403 Forbidden

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.

Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Require local
    Require ip 192.168.0

The Require local allows access from these ip's 127.0.0.1 & localhost & ::1.

The statement Require ip 192.168.0 will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so you have to make the access privilage amendements in the Virtual Host definition config file

First dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Hopefully you will have created a Virtual Host for your project and not be using the wamp\www folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.

Dont forget to restart Apache after making this change

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

jQuery click anywhere in the page except on 1 div

You can apply click on body of document and cancel click processing if the click event is generated by div with id menu_content, This will bind event to single element and saving binding of click with every element except menu_content

$('body').click(function(evt){    
       if(evt.target.id == "menu_content")
          return;
       //For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
       if($(evt.target).closest('#menu_content').length)
          return;             

      //Do processing of click event here for every element except with id menu_content

});

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

Positioning background image, adding padding

Updated Answer:

It's been commented multiple times that this is not the correct answer to this question, and I agree. Back when this answer was written, IE 9 was still new (about 8 months old) and many developers including myself needed a solution for <= IE 9. IE 9 is when IE started supporting background-origin. However, it's been over six and a half years, so here's the updated solution which I highly recommend over using an actual border. In case < IE 9 support is needed. My original answer can be found below the demo snippet. It uses an opaque border to simulate padding for background images.

_x000D_
_x000D_
#hello {
  padding-right: 10px;
  background-color:green;
  background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
  background-origin: content-box;
}
_x000D_
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
_x000D_
_x000D_
_x000D_

Original Answer:

you can fake it with a 10px border of the same color as the background:

http://jsbin.com/eparad/edit#javascript,html,live

#hello {
   border: 10px solid #e8e8e8;
   background-color: green;
   background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
               no-repeat scroll right center #e8e8e8;
}

Backbone.js fetch with parameters

Another example if you are using Titanium Alloy:

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });

How to add element into ArrayList in HashMap

#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next());  //name
al.add(s.next());  //category
al.add(s.nextInt()); //fee
d.put(id, al);
 }

ORDER BY the IN value list

I agree with all other posters that say "don't do that" or "SQL isn't good at that". If you want to sort by some facet of comments then add another integer column to one of your tables to hold your sort criteria and sort by that value. eg "ORDER BY comments.sort DESC " If you want to sort these in a different order every time then... SQL won't be for you in this case.

How to copy a file from remote server to local machine?

For example, your remote host is example.com and remote login name is user1:

scp [email protected]:/path/to/file /path/to/store/file

How do I deal with certificates using cURL while trying to access an HTTPS url?

For what it's worth, checking which curl is being run is significant too.

A user on a shared machine I maintain had been getting this error. But the cause turned out to be because they'd installed Anaconda (http://continuum.io). Doing so put Anaconda's binary path before the standard $PATH, and it comes with its own curl binary, which had trouble finding the default certs that were installed on this Ubuntu machine.

Plotting categorical data with pandas and matplotlib

You might find useful mosaic plot from statsmodels. Which can also give statistical highlighting for the variances.

from statsmodels.graphics.mosaicplot import mosaic
plt.rcParams['font.size'] = 16.0
mosaic(df, ['direction', 'colour']);

enter image description here

But beware of the 0 sized cell - they will cause problems with labels.

See this answer for details

How to access PHP session variables from jQuery function in a .js file?

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $( "#progressbar" ).progressbar({
            value: percent
        });
    };
})(jQuery);

Why is processing a sorted array faster than processing an unsorted array?

An official answer would be from

  1. Intel - Avoiding the Cost of Branch Misprediction
  2. Intel - Branch and Loop Reorganization to Prevent Mispredicts
  3. Scientific papers - branch prediction computer architecture
  4. Books: J.L. Hennessy, D.A. Patterson: Computer architecture: a quantitative approach
  5. Articles in scientific publications: T.Y. Yeh, Y.N. Patt made a lot of these on branch predictions.

You can also see from this lovely diagram why the branch predictor gets confused.

2-bit state diagram

Each element in the original code is a random value

data[c] = std::rand() % 256;

so the predictor will change sides as the std::rand() blow.

On the other hand, once it's sorted, the predictor will first move into a state of strongly not taken and when the values change to the high value the predictor will in three runs through change all the way from strongly not taken to strongly taken.


pandas DataFrame: replace nan values with average of columns

Pandas: How to replace NaN (nan) values with the average (mean), median or other statistics of one column

Say your DataFrame is df and you have one column called nr_items. This is: df['nr_items']

If you want to replace the NaN values of your column df['nr_items'] with the mean of the column:

Use method .fillna():

mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)

I have created a new df column called nr_item_ave to store the new column with the NaN values replaced by the mean value of the column.

You should be careful when using the mean. If you have outliers is more recommendable to use the median

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

Compiler error: "initializer element is not a compile-time constant"

You can certainly #define a macro as shown below. The compiler will replace "IMAGE_SEGMENT" with its value before compilation. While you will achieve defining a global lookup for your array, it is not the same as a global variable. When the macro is expanded, it works just like inline code and so a new image is created each time. So if you are careful in where you use the macro, then you would have effectively achieved creating a global variable.

#define IMAGE_SEGMENT [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];

Then use it where you need it as shown below. Each time the below code is executed, a new object is created with a new memory pointer.

imageSegment = IMAGE_SEGMENT

How to horizontally center a floating element of a variable width?

for 50% element

width: 50%;
display: block;
float: right;
margin-right: 25%;

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

No.

Sometimes you can quote the filename.

"C:\Program Files\Something"

Some programs will tolerate the quotes. Since you didn't provide any specific program, it's impossible to tell if quotes will work for you.

phpinfo() - is there an easy way for seeing it?

Use the command line.

touch /var/www/project1/html/phpinfo.php && echo '<?php phpinfo(); ?>' >> /var/www/project1/html/phpinfo.php && firefox --url localhost/project1/phpinfo.php

Something like that? Idk!

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

Using 'sudo apt-get install build-essentials'

I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:

sudo vi /etc/apt/sources.list

and added the following lines:

deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main

If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:

sudo apt-get update
sudo apt-get install build-essential

Hopefully this will help someone who had the same problem that I did.

Tooltips for cells in HTML table (no Javascript)

You can use css and the :hover pseudo-property. Here is a simple demo. It uses the following css:

a span.tooltip {display:none;}
a:hover span.tooltip {position:absolute;top:30px;left:20px;display:inline;border:2px solid green;}

Note that older browsers have limited support for :hover.

Initialize value of 'var' in C# to null

The var keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var keyword has a type. For instance, you'll find that the following code outputs "String".

var myString = "";
Console.Write(myString.GetType().Name);

Furthermore, the code above is equivalent to:

String myString = "";
Console.Write(myString.GetType().Name);

The var keyword is simply C#'s way of saying "I can figure out the type for myString from the context, so don't worry about specifying the type."

var myVariable = (MyType)null or MyType myVariable = null should work because you are giving the C# compiler context to figure out what type myVariable should will be.

For more information:

Sort a List of objects by multiple fields

You have to write your own compareTo() method that has the Java code needed to perform the comparison.

If we wanted for example to compare two public fields, campus, then faculty, we might do something like:

int compareTo(GraduationCeremony gc)
{
    int c = this.campus.compareTo(gc.campus);

    if( c != 0 )
    {
        //sort by campus if we can
        return c;
    }
    else
    {
        //campus equal, so sort by faculty
        return this.faculty.compareTo(gc.faculty);
    }
}

This is simplified but hopefully gives you an idea. Consult the Comparable and Comparator docs for more info.

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

How to read a text file into a string variable and strip newlines?

It's hard to tell exactly what you're after, but something like this should get you started:

with open ("data.txt", "r") as myfile:
    data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

Only Objective-C is allowed by now... but since a few months ago you are allowed to write scripts that will be interpreted in your application.

So you may be able to write a LUA interpreter or a Python interpreter, then write some part of your application in this scripting language. If you want your application accepted on the App Store, these scripts have to be bundled with the application (your application cannot download it from the Internet for example)

see new app store rules

Get decimal portion of a number with JavaScript

The following works regardless of the regional settings for decimal separator... on the condition only one character is used for a separator.

var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
  return "0";
return strungNumber.substring(integer.length + 1);

It ain't pretty, but it's accurate.

How to clear cache of Eclipse Indigo

I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.

Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html

How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Read file data without saving it in Flask

FileStorage contains stream field. This object must extend IO or file object, so it must contain read and other similar methods. FileStorage also extend stream field object attributes, so you can just use file.read() instead file.stream.read(). Also you can use save argument with dst parameter as StringIO or other IO or file object to copy FileStorage.stream to another IO or file object.

See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

CSS center display inline block?

You can also do this with positioning, set parent div to relative and child div to absolute.

.wrapper {
      position: relative;
  }
.childDiv {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
  }

How unique is UUID?

There is more than one type of UUID, so "how safe" depends on which type (which the UUID specifications call "version") you are using.

  • Version 1 is the time based plus MAC address UUID. The 128-bits contains 48-bits for the network card's MAC address (which is uniquely assigned by the manufacturer) and a 60-bit clock with a resolution of 100 nanoseconds. That clock wraps in 3603 A.D. so these UUIDs are safe at least until then (unless you need more than 10 million new UUIDs per second or someone clones your network card). I say "at least" because the clock starts at 15 October 1582, so you have about 400 years after the clock wraps before there is even a small possibility of duplications.

  • Version 4 is the random number UUID. There's six fixed bits and the rest of the UUID is 122-bits of randomness. See Wikipedia or other analysis that describe how very unlikely a duplicate is.

  • Version 3 is uses MD5 and Version 5 uses SHA-1 to create those 122-bits, instead of a random or pseudo-random number generator. So in terms of safety it is like Version 4 being a statistical issue (as long as you make sure what the digest algorithm is processing is always unique).

  • Version 2 is similar to Version 1, but with a smaller clock so it is going to wrap around much sooner. But since Version 2 UUIDs are for DCE, you shouldn't be using these.

So for all practical problems they are safe. If you are uncomfortable with leaving it up to probabilities (e.g. your are the type of person worried about the earth getting destroyed by a large asteroid in your lifetime), just make sure you use a Version 1 UUID and it is guaranteed to be unique (in your lifetime, unless you plan to live past 3603 A.D.).

So why doesn't everyone simply use Version 1 UUIDs? That is because Version 1 UUIDs reveal the MAC address of the machine it was generated on and they can be predictable -- two things which might have security implications for the application using those UUIDs.

Standard way to embed version into python package?

If you use CVS (or RCS) and want a quick solution, you can use:

__version__ = "$Revision: 1.1 $"[11:-2]
__version_info__ = tuple([int(s) for s in __version__.split(".")])

(Of course, the revision number will be substituted for you by CVS.)

This gives you a print-friendly version and a version info that you can use to check that the module you are importing has at least the expected version:

import my_module
assert my_module.__version_info__ >= (1, 1)

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

Download File to server from URL

private function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen ($url, 'rb');
    if ($file) {
        $newf = fopen ($newfname, 'wb');
        if ($newf) {
            while(!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

Initial size for the ArrayList

Being late to this, but after Java 8, I personally find this following approach with the Stream API more concise and can be an alternative to the accepted answer.

For example,

Arrays.stream(new int[size]).boxed().collect(Collectors.toList())

where size is the desired List size and without the disadvantage mentioned here, all elements in the List are initialized as 0.

(I did a quick search and did not see stream in any answers posted - feel free to let me know if this answer is redundant and I can remove it)

Case vs If Else If: Which is more efficient?

Wikipedia's Switch statement entry is pretty big and actually pretty good. Interesting points:

  • Switches are not inherently fast. It depends on the language, compiler, and specific use.
  • A compiler may optimize switches using jump tables or indexed function pointers.
  • The statement was inspired by some interesting math from Stephen Kleene (and others).

For a strange and interesting optimization using a C switch see Duff's Device.

Array String Declaration

use:

String[] mStrings = new String[title.length];

Object reference not set to an instance of an object.

I know this was posted about a year ago, but this is for users for future reference.

I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.

while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.

if (email == null)
{     
     break;    
}
else
{    
     // your code here    
}

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Initialize a string in C to empty string

calloc allocates the requested memory and returns a pointer to it. It also sets allocated memory to zero.

In case you are planning to use your string as empty string all the time:

char *string = NULL;
string = (char*)calloc(1, sizeof(char));

In case you are planning to store some value in your string later:

char *string = NULL;
int numberOfChars = 50; // you can use as many as you need
string = (char*)calloc(numberOfChars + 1, sizeof(char));

How can I make one python file run another?

from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

What's the difference between "&nbsp;" and " "?

When having line-breaks, the line will not break when you use an $bnsp; because it's a 'non-breaking space'. This can be important if you have certain product-names or such, that always shall be written together.

Can be interesting if you (have to) use a whitespace as delimiter in numbers, like 12344567, that is displayed 12 344 567 in France. Without the   the line would break in the middle of the number, very ugly. Test:12 344 567

Clear Application's Data Programmatically

combine code from 2 answers:

Here is the resulting combined source based answer

private void clearAppData() {
    try {
        // clearing app data
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData(); // note: it has a return value!
        } else {
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } 
}

Where is the <conio.h> header file on Linux? Why can't I find <conio.h>?

A popular Linux library which has similar functionality would be ncurses.

Attach Authorization header for all axios requests

Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.

export default () => {
    axios.interceptors.request.use(function (requestConfig) {
        if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
            const token = localStorage.token;
            requestConfig.headers['Authorization'] = `Bearer ${token}`;
        }

        return requestConfig;
    }, function (error) {
        return Promise.reject(error);
    });

}

Reset all the items in a form

I recently had to do this for Textboxes and Checkboxes but using JavaScript ...

How to reset textbox and checkbox controls in an ASP.net document

Here is the code ...

<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>

<script type="text/javascript">
      function ResetForm() {
          //get the all the Input type elements in the document
          var AllInputsElements = document.getElementsByTagName('input');
          var TotalInputs = AllInputsElements.length;

          //we have to find the checkboxes and uncheck them
          //note: <asp:checkbox renders to <input type="checkbox" after compiling, which is why we use 'input' above
          for(var i=0;i< TotalInputs ; i++ )
          {
            if(AllInputsElements[i].type =='checkbox')
            {
                AllInputsElements[i].checked = false;
            }
          }

          //reset all textbox controls
          $('input[type=text], textarea').val('');

          Page_ClientValidateReset();
          return false;
      }

      //This function resets all the validation controls so that they don't "fire" up
      //during a post-back.
      function Page_ClientValidateReset() {
          if (typeof (Page_Validators) != "undefined") {
              for (var i = 0; i < Page_Validators.length; i++) {
                  var validator = Page_Validators[i];
                  validator.isvalid = true;
                  ValidatorUpdateDisplay(validator);
              }
          }
      }
</script>

And call it with a button or any other method ...

<asp:button id="btnRESET" runat="server" onclientclick="return ResetForm();" text="RESET" width="100px"></asp:button>

If you don't use ValidationControls on your website, just remove all the code refering to it above and the call Page_ClientValidateReset();

I am sure you can expand it for any other control using the DOM. And since there is no post to the server, it's faster and no "flashing" either.

scp files from local to remote machine error: no such file or directory

Be sure the folder from where you send the file does not contain space !

I was trying to send a file to a remote server from my windows machine from VS code terminal, and I got this error even if the file was here.

It's because the folder where the file was contained space in its name...

IN vs OR in the SQL WHERE Clause

The best way to find out is looking at the Execution Plan.


I tried it with Oracle, and it was exactly the same.

CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );

SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );

Even though the query uses IN, the Execution Plan says that it uses OR:

--------------------------------------------------------------------------------------    
| Id  | Operation         | Name             | Rows  | Bytes | Cost (%CPU)| Time     |    
--------------------------------------------------------------------------------------    
|   0 | SELECT STATEMENT  |                  |     8 |  1416 |   163   (2)| 00:00:02 |    
|*  1 |  TABLE ACCESS FULL| PERFORMANCE_TEST |     8 |  1416 |   163   (2)| 00:00:02 |    
--------------------------------------------------------------------------------------    

Predicate Information (identified by operation id):                                       
---------------------------------------------------                                       

   1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR                
              "OBJECT_NAME"='DBMS_STANDARD')                                              

Sequence contains no elements?

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

How to find the Target *.exe file of *.appref-ms

The app is stored in %LocalAppData% in your %UserProfile%. So the full path could be:

C:\Users\username\AppData\Local\GitHub

Is it possible only to declare a variable without assigning any value in Python?

You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like

value = sequence.index(blarg)

AndroidStudio gradle proxy

In Android Studio -> Preferences -> Gradle, pass the proxy details as VM options.

Gradle VM Options -Dhttp.proxyHost=www.somehost.org -Dhttp.proxyPort=8080 etc.

*In 0.8.6 Beta Gradle is under File->Settings (Ctrl+Alt+S, on Windows and Linux)

How to convert an address to a latitude/longitude?

If you need a one off solution, you can try: https://addresstolatlong.com/

I've used it for a long time and it has worked pretty well for me.

How do I find out what is hammering my SQL Server?

You can run the SQL Profiler, and filter by CPU or Duration so that you're excluding all the "small stuff". Then it should be a lot easier to determine if you have a problem like a specific stored proc that is running much longer than it should (could be a missing index or something).

Two caveats:

  • If the problem is massive amounts of tiny transactions, then the filter I describe above would exclude them, and you'd miss this.
  • Also, if the problem is a single, massive job (like an 8-hour analysis job or a poorly designed select that has to cross-join a billion rows) then you might not see this in the profiler until it is completely done, depending on what events you're profiling (sp:completed vs sp:statementcompleted).

But normally I start with the Activity Monitor or sp_who2.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Removing time from a Date object?

You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static Date removeTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

}

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Just go to vmvare edit->preferences->shared vms. Click on change settings and disable sharing.click on OK.xampp will work fine.

If list index exists, do X

Do not let any space in front of your brackets.

Example:

n = input ()
         ^

Tip: You should add comments over and/or under your code. Not behind your code.


Have a nice day.

Difference between volatile and synchronized in Java

tl;dr:

There are 3 main issues with multithreading:

1) Race Conditions

2) Caching / stale memory

3) Complier and CPU optimisations

volatile can solve 2 & 3, but can't solve 1. synchronized/explicit locks can solve 1, 2 & 3.

Elaboration:

1) Consider this thread unsafe code:

x++;

While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.

Using synchronized on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x was 1, and 2 threads try to preform x++ we know in the end it will be equal to 3. So it solves the race condition problem.

synchronized (this) {
   x++; // no problem now
}

Marking x as volatile does not make x++; atomic, so it doesn't solve this problem.

2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.

Consider that on one thread, x = 10;. And somewhat later, in another thread, x = 20;. The change in value of x might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20) the answer will be false.

Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.

Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.

3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.

Consider the following code:

boolean b = false;
int x = 10;

void threadA() {
    x = 20;
    b = true;
}

void threadB() {
    if (b) {
        System.out.println(x);
    }
}

You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b to true), as b is set to true only after x is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b as volatile ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.

Note that before Java 5 New Memory Model, volatile didn’t solve this issue.

How to change the text color of first select option

For Option 1 used as the placeholder:

select:invalid { color:grey; }

All other options:

select:valid { color:black; }

How to get row count in sqlite using Android?

Using DatabaseUtils.queryNumEntries():

public long getProfilesCount() {
    SQLiteDatabase db = this.getReadableDatabase();
    long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
    db.close();
    return count;
}

or (more inefficiently)

public int getProfilesCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    cursor.close();
    return count;
}

In Activity:

int profile_counts = db.getProfilesCount();
    db.close();

Transparent ARGB hex value

Transparency is controlled by the alpha channel (AA in #AARRGGBB). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.

To get a fully transparent color set the alpha to zero. RR, GG and BB are irrelevant in this case because no color will be visible. This means #00FFFFFF ("transparent White") is the same color as #00F0F8FF ("transparent AliceBlue"). To keep it simple one chooses black (#00000000) or white (#00FFFFFF) if the color does not matter.

In the table you linked to you'll find Transparent defined as #00FFFFFF.

How do I remove trailing whitespace using a regular expression?

In Java:



String str = "    hello world  ";

// prints "hello world" 
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));


Android - Back button in the title bar

first of all in onCreate Function add the following line

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and then add the following function in the code:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

C# how to wait for a webpage to finish loading before continuing

while (true)
        {//ie is the WebBrowser object
            if (ie.ReadyState == tagREADYSTATE.READYSTATE_COMPLETE)
            {
                break;
            }
            Thread.Sleep(500);
        }

I used this way to wait untill the page loads.

jQuery ajax error function

Try this:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

If you want to inform your frontend about a validation error, try to return json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {
   console.log(data.error);
}

Your asp script schould return:

{"error": true}

How to loop through a collection that supports IEnumerable?

or even a very classic old fashion method

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // do your stuff   
}

maybe you would like this method also :-)

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

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

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

Custom Cell Row Height setting in storyboard is not responding

On dynamic cells, rowHeight set on the UITableView always overrides the individual cells' rowHeight.

But on static cells, rowHeight set on individual cells can override UITableView's.

Not sure if it's a bug, Apple might be intentionally doing this?

How to select the first, second, or third element with a given class name?

This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.

I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type which, for my situation, worked. (So, thanks for that, @Bdwey.)

I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.

Turns out as follows: div.myclass:nth-of-type(2) does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening divs between your div.myclass instances.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

_x000D_
_x000D_
div {_x000D_
  margin-bottom: 2em;_x000D_
  border: red solid 1px;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
  font-size: 12pt;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
  background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
  background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
  background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
  <h1 class="A">h1.A #1</h1>_x000D_
  <h1 class="A">h1.A #2</h1>_x000D_
  <h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h2 class="A">h2.A #1</h2>_x000D_
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
  <h2 class="A">h2.A #2</h2>_x000D_
  <h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  <h3 class="A">h3.A #1</h3>_x000D_
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
  <h3 class="A">h3.A #2</h3>_x000D_
  <h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Java ArrayList Index

Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.

How to generate a random string in Ruby

To make your first into one statement:

(0...8).collect { |n| value  << (65 + rand(25)).chr }.join()

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Java collections convert a string to a list of characters

List<String> result = Arrays.asList("abc".split(""));

How to install Python packages from the tar.gz file without using pip install

You may use pip for that without using the network. See in the docs (search for "Install a particular source archive file"). Any of those should work:

pip install relative_path_to_seaborn.tar.gz    
pip install absolute_path_to_seaborn.tar.gz    
pip install file:///absolute_path_to_seaborn.tar.gz    

Or you may uncompress the archive and use setup.py directly with either pip or python:

cd directory_containing_tar.gz
tar -xvzf seaborn-0.10.1.tar.gz
pip install seaborn-0.10.1
python setup.py install

Of course, you should also download required packages and install them the same way before you proceed.

Using str_replace so that it only acts on the first match?

$str = "Hello there folks!"
$str_ex = explode("there, $str, 2);   //explodes $string just twice
                                      //outputs: array ("Hello ", " folks")
$str_final = implode("", $str_ex);    // glues above array together
                                      // outputs: str("Hello  folks")

There is one more additional space but it didnt matter as it was for backgound script in my case.

Scrolling a div with jQuery

I don't know if this is exactly what you want, but did you know you can use the CSS overflow property to create scrollbars?

CSS:

div.box{
  width: 200px;
  height: 200px;
  overflow: scroll;
}

HTML:

<div class="box">
  All your text content...
</div>

SELECT with LIMIT in Codeigniter

Try this...

function nationList($limit=null, $start=null) {
    if ($this->session->userdata('language') == "it") {
        $this->db->select('nation.id, nation.name_it as name');
    }

    if ($this->session->userdata('language') == "en") {
        $this->db->select('nation.id, nation.name_en as name');
    }

    $this->db->from('nation');
    $this->db->order_by("name", "asc");

    if ($limit != '' && $start != '') {
       $this->db->limit($limit, $start);
    }
    $query  = $this->db->get();

    $nation = array();
    foreach ($query->result() as $row) {
        array_push($nation, $row);
    }

    return $nation;     
}

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

For anyone trying to do this in asp.net core. You can use claims.

public class CustomEmailProvider : IUserIdProvider
{
    public virtual string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
    }
}

Any identifier can be used, but it must be unique. If you use a name identifier for example, it means if there are multiple users with the same name as the recipient, the message would be delivered to them as well. I have chosen email because it is unique to every user.

Then register the service in the startup class.

services.AddSingleton<IUserIdProvider, CustomEmailProvider>();

Next. Add the claims during user registration.

var result = await _userManager.CreateAsync(user, Model.Password);
if (result.Succeeded)
{
    await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Model.Email));
}

To send message to the specific user.

public class ChatHub : Hub
{
    public async Task SendMessage(string receiver, string message)
    {
        await Clients.User(receiver).SendAsync("ReceiveMessage", message);
    }
}

Note: The message sender won't be notified the message is sent. If you want a notification on the sender's end. Change the SendMessage method to this.

public async Task SendMessage(string sender, string receiver, string message)
{
    await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", message);
}

These steps are only necessary if you need to change the default identifier. Otherwise, skip to the last step where you can simply send messages by passing userIds or connectionIds to SendMessage. For more

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

How to open local files in Swagger-UI

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",

How to convert MySQL time to UNIX timestamp using PHP?

From one of my other posts, getting a unixtimestamp:

$unixTimestamp = time();

Converting to mysql datetime format:

$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);

Getting some mysql timestamp:

$mysqlTimestamp = '2013-01-10 12:13:37';

Converting it to a unixtimestamp:

$unixTimestamp = strtotime('2010-05-17 19:13:37');

...comparing it with one or a range of times, to see if the user entered a realistic time:

if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}

Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:

if(ctype_digit($_GET["UpdateTimestamp"]))
{...}

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

What's a good hex editor/viewer for the Mac?

There are probably better options, but I use and kind of like TextWrangler for basic hex editing. File -> hex Dump File

SQL Query for Student mark functionality

SELECT          subjectname,
                studentname 
FROM            student s 
INNER JOIN      mark m 
  ON            s.studid = m.studid 
INNER JOIN      subject su 
  ON            su.subjectid = m.subjectid 
INNER JOIN (
  SELECT        subjectid,
                max(value) AS maximum 
  FROM          mark 
  GROUP BY      subjectid
)               highmark h 
  ON            h.subjectid = m.subjectid 
  AND           h.maximum = m.value;

angular2 manually firing click event on particular element

Angular4

Instead of

    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);

use

    this.fileInput.nativeElement.dispatchEvent(event);

because invokeElementMethod won't be part of the renderer anymore.

Angular2

Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent to fire the event:

import { Component, Renderer, ElementRef, ViewChild } from '@angular/core';
@Component({
  ...
  template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
  @ViewChild('fileInput') fileInput:ElementRef;

  constructor(private renderer:Renderer) {}

  showImageBrowseDlg() {
    // from http://stackoverflow.com/a/32010791/217408
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);
  }
}

Update

Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well

this.fileInput.nativeElement.click()

See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

How to set css style to asp.net button?

You can assign a class to your ASP.NET Button and then apply the desired style to it.

<asp:Button class="mybtn" Text="Button" runat="server"></asp:Button>

CSS:

.mybtn
{
   border:1px solid Red;
   //some more styles
}

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

How to update std::map after using the find method?

You can use std::map::at member function, it returns a reference to the mapped value of the element identified with key k.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

How to check internet access on Android? InetAddress never times out

if(isConnected()){
                Toast.makeText(getApplication(),"Thank you",Toast.LENGTH_SHORT).show();
        }
        else{

            AlertDialog.Builder builder =
                    new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
            builder.setTitle("Amar Bhat");
            builder.setMessage("Oops...You are not connected to Internet!!!");
            builder.setPositiveButton("OK", null);
            builder.setNegativeButton("Cancel", null);
            builder.show();
            //Toast.makeText(getApplication(),"You are not connected",Toast.LENGTH_SHORT).show();
        }




//And outside the class define isConnected()

 public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

// In minifest add these permission
<uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to get HQ youtube thumbnails?

Depending on the resolution you need, you can use a different URL:

Default Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

High Quality Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

Medium Quality

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Standard Definition

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Maximum Resolution

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Guys remember that you can use the try catch end event

Dim Green as integer

Try
    Green = InputBox("Please enter a value for green")
    Catch ex as Exception
        MsgBox("Green must be a valid integer!")
End Try

How do you read scanf until EOF in C?

I guess best way to do this is ...

int main()
{
    char str[100];
    scanf("[^EOF]",str);
    printf("%s",str);
    return 0;     
}

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This works perfectly for me, not matter how the date was coded previously.

library(lubridate)
data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

Outlets cannot be connected to repeating content iOS

Click on simulator , Navigate to Window and enable Device Bezels

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

Android SDK Build Tools are exactly what the name says they are; tools for building Android Applications.It is very important to use the latest build tools version (selected automatically by your IDE via the Android SDK) but the reason the old versions are left there is to support backward compatibility, that is If your projects depend on older versions of the Build Tools.

How do I tokenize a string in C++?

boost::tokenizer is your friend, but consider making your code portable with reference to internationalization (i18n) issues by using wstring/wchar_t instead of the legacy string/char types.

#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>

using namespace std;
using namespace boost;

typedef tokenizer<char_separator<wchar_t>,
                  wstring::const_iterator, wstring> Tok;

int main()
{
  wstring s;
  while (getline(wcin, s)) {
    char_separator<wchar_t> sep(L" "); // list of separator characters
    Tok tok(s, sep);
    for (Tok::iterator beg = tok.begin(); beg != tok.end(); ++beg) {
      wcout << *beg << L"\t"; // output (or store in vector)
    }
    wcout << L"\n";
  }
  return 0;
}

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

HTML5 placeholder css padding

I've created a fiddle using your screenshot as a background image and stripping out the extra mark-up, and it seems to work fine

http://jsfiddle.net/fLdQG/2/ (webkit browser required)

Does this work for you? If not, can you update the fiddle with your exact mark-up and CSS?