Programs & Examples On #Routing

Routing is the process of selecting paths in a network along which to send network traffic. For the process of associating URLs to content, use the tag url-routing instead.

Send data through routing paths in Angular

@dev-nish Your code works with little tweaks in them. make the

const navigationExtras: NavigationExtras = {
  state: {
    transd: 'TRANS001',
    workQueue: false,
    services: 10,
    code: '003'
  }
};

into

let navigationExtras: NavigationExtras = {
  state: {
    transd: '',
    workQueue: ,
    services: ,
    code: ''
  }
};

then if you want to specifically sent a type of data, for example, JSON as a result of a form fill you can send the data in the same way as explained before.

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

/Artist/GetImages/cher/api-key

you could add a route like:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

Passive Link in Angular 2 - <a href=""> equivalent

I am using this workaround with css:

/*** Angular 2 link without href ***/
a:not([href]){
    cursor: pointer; 
    -webkit-user-select: none; 
    -moz-user-select: none; 
    user-select: none
}

html

<a [routerLink]="/">My link</a>

Hope this helps

How to get current route in Symfony 2?

For anybody that need current route for Symfony 3, this is what I use

<?php
   $request = $this->container->get('router.request_context');
   //Assuming you are on user registration page like https://www.yoursite.com/user/registration
   $scheme = $request->getScheme(); //This will return https
   $host = $request->getHost(); // This will return www.yoursite.com
   $route = $request->getPathInfo(); // This will return user/registration(don't forget this is registrationAction in userController
   $name = $request->get('_route'); // This will return the name.
?>

Angular2 Routing with Hashtag to page anchor

Use this for the router module in app-routing.module.ts:

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    useHash: true,
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled',
    scrollOffset: [0, 64]
  })],
  exports: [RouterModule]
})

This will be in your HTML:

<a href="#/users/123#userInfo">

A potentially dangerous Request.Path value was detected from the client (*)

When dealing with Uniform Resource Locator(URL) s there are certain syntax standards, in this particular situation we are dealing with Reserved Characters.

As up to RFC 3986, Reserved Characters may (or may not) be defined as delimiters by the generic syntax, by each scheme-specific syntax, or by the implementation-specific syntax of a URI's dereferencing algorithm; And asterisk(*) is a Reserved Character.

The best practice is to use Unreserved Characters in URLs or you can try encoding it.

Keep digging :

HttpContext.Current.Session is null when routing requests

I think this part of code make changes to the context.

 Page page = BuildManager.CreateInstanceFromVirtualPath(
                        m_VirtualPath, 
                        typeof(Page)) as Page;// IHttpHandler;

Also this part of code is useless:

 if (page != null)
 {
     return page;
 }
 return page;

It will always return the page wither it's null or not.

How do I redirect to the previous action in ASP.NET MVC?

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

laravel throwing MethodNotAllowedHttpException

I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource which takes care of GET, POST, and other requests.

In my case I left my route as is:

Route::resource('file', 'FilesController');

And simply modified my form to submit to the store function in my FilesController

{{ Form::open(array('route' => 'file.store')) }}

This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST route. This is an option but it's not necessary.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

How to use absolute path in twig functions

I've used the following advice from the docs https://symfony.com/doc/current/console/request_context.html to get absolute urls in emails:

# config/services.yaml
parameters:
    router.request_context.host: 'example.org'
    router.request_context.scheme: 'https'

S3 Static Website Hosting Route All Paths to Index.html

It's tangential, but here's a tip for those using Rackt's React Router library with (HTML5) browser history who want to host on S3.

Suppose a user visits /foo/bear at your S3-hosted static web site. Given David's earlier suggestion, redirect rules will send them to /#/foo/bear. If your application's built using browser history, this won't do much good. However your application is loaded at this point and it can now manipulate history.

Including Rackt history in our project (see also Using Custom Histories from the React Router project), you can add a listener that's aware of hash history paths and replace the path as appropriate, as illustrated in this example:

import ReactDOM from 'react-dom';

/* Application-specific details. */
const route = {};

import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';

const history = useRouterHistory(createHistory)();

history.listen(function (location) {
  const path = (/#(\/.*)$/.exec(location.hash) || [])[1];
  if (path) history.replace(path);
});

ReactDOM.render(
  <Router history={history} routes={route}/>,
  document.body.appendChild(document.createElement('div'))
);

To recap:

  1. David's S3 redirect rule will direct /foo/bear to /#/foo/bear.
  2. Your application will load.
  3. The history listener will detect the #/foo/bear history notation.
  4. And replace history with the correct path.

Link tags will work as expected, as will all other browser history functions. The only downside I've noticed is the interstitial redirect that occurs on initial request.

This was inspired by a solution for AngularJS, and I suspect could be easily adapted to any application.

AngularJS - How can I do a redirect with a full page load?

Try this

$window.location.href="#page-name";
$window.location.reload();

My Routes are Returning a 404, How can I Fix Them?

the simple Commands with automatic loads the dependencies

composer dump-autoload

and still getting that your some important files are missing so go here to see whole procedure

https://codingexpertise.blogspot.com/2018/11/laravel-new.html

Is it possible to access an SQLite database from JavaScript?

You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Can you write nested functions in JavaScript?

Functions are first class objects that can be:

  • Defined within your function
  • Created just like any other variable or object at any point in your function
  • Returned from your function (which may seem obvious after the two above, but still)

To build on the example given by Kenny:

   function a(x) {
      var w = function b(y) {
        return x + y;
      }
      return w;
   };

   var returnedFunction = a(3);
   alert(returnedFunction(2));

Would alert you with 5.

How to create a Java / Maven project that works in Visual Studio Code?

Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-

  1. Download VS Code and Apache Maven and install both.
  2. Install the Visual Studio extension pack for Java - e.g. by pasting this URL into a web browser: vscode:extension/vscjava.vscode-java-pack and then clicking on the green Install button after it opens in VS Code.
  3. NOTE: See the comment from ADTC for an "Easier GUI version of step 3...(Skip step 4)." If necessary, the Maven quick start archetype could be used to generate a new Maven project in an appropriate local folder: mvn archetype:generate -DgroupId=com.companyname.appname-DartifactId=appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname and src/main/test/com/companyname/appname to begin with and a sample "Hello World!" Java file named appname.java and associated unit test named appnameTest.java).*
  4. Open the Maven project folder in VS Code via File menu -> Open Folder... and select the appname folder.
  5. Open the Command Palette (via the View menu or by right-clicking) and type in and select Tasks: Configure task then select Create tasks.json from template.
  6. Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:

    {
        "label": "compile",
        "type": "shell",
        "command": "mvn -B compile",
        "group": "build"
    },
    
  7. Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target folder at the same level as the src folder with the compiled class files in the target\classes folder.


Addendum: How to run/debug a class

Following a question in the comments, here are some steps for running/debugging:-

  1. Show the Debug view if it is not already shown (via View menu - Debug or CtrlShiftD).
  2. Click on the green arrow in the Debug view and select "Java".
  3. Assuming it hasn't already been created, a message "launch.json is needed to start the debugger. Do you want to create it now?" will appear - select "Yes" and then select "Java" again.
  4. Enter the fully qualified name of the main class (e.g. com.companyname.appname.App) in the value for "mainClass" and save the file.
  5. Click on the green arrow in the Debug view again.

Find package name for Android apps to use Intent to launch Market app from web

Here are easy way to get app's full package. we can use astro file manager app. You can get it on android market. Astro app manager show us app's full package.

Checking for empty queryset in Django

To check the emptiness of a queryset:

if orgs.exists():
    # Do something

or you can check for a the first item in a queryset, if it doesn't exist it will return None:

if orgs.first():
    # Do something

How to print color in console using System.out.println?

To strikeout:

public static final String ANSI_STRIKEOUT_BLACK = "\u001B[30;9m";
public static final String ANSI_STRIKEOUT_RED = "\u001B[31;9m";
public static final String ANSI_STRIKEOUT_GREEN = "\u001B[32;9m";
public static final String ANSI_STRIKEOUT_YELLOW = "\u001B[33;9m";
public static final String ANSI_STRIKEOUT_BLUE = "\u001B[34;9m";
public static final String ANSI_STRIKEOUT_PURPLE = "\u001B[35;9m";
public static final String ANSI_STRIKEOUT_CYAN = "\u001B[36;9m";
public static final String ANSI_STRIKEOUT_WHITE = "\u001B[37;9m";

flutter run: No connected devices

Some times the issue is with the device connection and it's driver

if you already turned on the Developer Option and USB debugging and still unable to connect your Device

you must try this one as it's officially from GOOGLE.

Install OEM USB drivers :

https://developer.android.com/studio/run/oem-usb

Sort array of objects by single key with date value

You can create a closure and pass it that way here is my example working

$.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)', 
  function(responce) {

    var filter = 'event_clearance_group', //sort by key group name
    data = responce; 

    var compare = function (filter) {
        return function (a,b) {
            var a = a[filter],
                b = b[filter];

            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        };
    };

    filter = compare(filter); //set filter

    console.log(data.sort(filter));
});

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

iOS start Background Thread

If you use performSelectorInBackground:withObject: to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.

You'd probably be better off using Grand Central Dispatch, though:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self getResultSetFromDB:docids];
});

GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.


Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.

Safe width in pixels for printing web pages?

A printer doesn't understand pixels, it understand dots (pt in CSS). The best solution is to write an extra CSS for printing, with all of its measures in dots.

Then, in your HTML code, in head section, put:

<link href="style.css" rel="stylesheet" type="text/css" media="screen">
<link href="style_print.css" rel="stylesheet" type="text/css" media="print">

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Which UUID version to use?

If you want a random number, use a random number library. If you want a unique identifier with effectively 0.00...many more 0s here...001% chance of collision, you should use UUIDv1. See Nick's post for UUIDv3 and v5.

UUIDv1 is NOT secure. It isn't meant to be. It is meant to be UNIQUE, not un-guessable. UUIDv1 uses the current timestamp, plus a machine identifier, plus some random-ish stuff to make a number that will never be generated by that algorithm again. This is appropriate for a transaction ID (even if everyone is doing millions of transactions/s).

To be honest, I don't understand why UUIDv4 exists... from reading RFC4122, it looks like that version does NOT eliminate possibility of collisions. It is just a random number generator. If that is true, than you have a very GOOD chance of two machines in the world eventually creating the same "UUID"v4 (quotes because there isn't a mechanism for guaranteeing U.niversal U.niqueness). In that situation, I don't think that algorithm belongs in a RFC describing methods for generating unique values. It would belong in a RFC about generating randomness. For a set of random numbers:

chance_of_collision = 1 - (set_size! / (set_size - tries)!) / (set_size ^ tries)

What characters are valid for JavaScript variable names?

Actually, ECMAScript says on page 15: That an identifier may start with a $, an underscore or a UnicodeLetter, and then it goes on (just below that) to specify that a UnicodeLetter can be any character from the unicode catagories, Lo, Ll, Lu, Lt, Lm and Nl. And when you look up those catagories you will see that this opens up a lot more possibilities than just latin letters. Just search for "unicode catagories" in google and you can find them.

Can someone explain Microsoft Unity?

Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.

public interface ICalculator
{
    void Add(int a, int b);
}

public class Calculator : ICalculator
{
    public void Add(int a, int b)
    {
        return a + b;
    }
}

You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).

IoCLlibrary.Register<ICalculator>.Return<Calculator>();

So now when you want an instance of an ICalculator you just...

Calculator calc = IoCLibrary.Resolve<ICalculator>();

IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.

Now let's say you have a class that relies on an ICalculator to be present you could have..

public class BankingSystem
{
    public BankingSystem(ICalculator calc)
    {
        _calc = calc;
    }

    private ICalculator _calc;
}

And you can setup the library to inject a object into the constructor when it's created.

So DI or Dependency Injection means to inject any object another might require.

Getting error "No such module" using Xcode, but the framework is there

I found that the Import Paths in the Build Settings was wrong for a custom (MySQL) module. After pointing that to the right direction the message was gone.

Rails 4: how to use $(document).ready() with turbo-links

I found the following article which worked great for me and details the use of the following:

var load_this_javascript = function() { 
  // do some things 
}
$(document).ready(load_this_javascript)
$(window).bind('page:change', load_this_javascript)

Root element is missing

I had the same problem when i have trying to read xml that was extracted from archive to memory stream.

 MemoryStream SubSetupStream = new MemoryStream();
        using (ZipFile archive = ZipFile.Read(zipPath))
        {
            archive.Password = "SomePass";
            foreach  (ZipEntry file in archive)
            {
                file.Extract(SubSetupStream);
            }
        }

Problem was in these lines:

XmlDocument doc = new XmlDocument();
    doc.Load(SubSetupStream);

And solution is (Thanks to @Phil):

        if (SubSetupStream.Position>0)
        {
            SubSetupStream.Position = 0;
        }

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

C: printf a float value

Use %.6f. This will print 6 decimals.

How to avoid pressing Enter with getchar() for reading a single character only?

By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush:

while((c=getchar())!= EOF)      
{
    putchar(c);
    fflush(stdout);
}

type object 'datetime.datetime' has no attribute 'datetime'

I run into the same error maybe you have already imported the module by using only import datetime so change form datetime import datetime to only import datetime. It worked for me after I changed it back.

Check whether a string is not null and not empty

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

Strings.nullToEmpty(str).isEmpty(); 
// or
Strings.isNullOrEmpty(str);

Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).

Guava's version of Commons Lang isBlank would be:

Strings.nullToEmpty(str).trim().isEmpty()

I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').

Installing Pandas on Mac OSX

In Mac terminal (we can launch Mac Terminal by searching in spotlight search Command + space) Now, use the command:

pip3 install pandas

As I'm using Python Version 3 I need to use pip3 install pandas.

If you are using python version 2 than use Command:

pip install pandas

Make sure pip is already installed in the device

How to include PHP files that require an absolute path?

You could define a constant with the path to the root directory of your project, and then put that at the beginning of the path.

Automatically scroll down chat div

after append in JQuery,just add this line

<script>
    $("#messages").animate({ scrollTop: 20000000 }, "slow");
</script>

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

How to delete duplicate rows in SQL Server?

If you have the ability to add a column to the table temporarily, this was a solution that worked for me:

ALTER TABLE dbo.DUPPEDTABLE ADD RowID INT NOT NULL IDENTITY(1,1)

Then perform a DELETE using a combination of MIN and GROUP BY

DELETE b
FROM dbo.DUPPEDTABLE b
WHERE b.RowID NOT IN (
                     SELECT MIN(RowID) AS RowID
                     FROM dbo.DUPPEDTABLE a WITH (NOLOCK)
                     GROUP BY a.ITEM_NUMBER,
                              a.CHARACTERISTIC,
                              a.INTVALUE,
                              a.FLOATVALUE,
                              a.STRINGVALUE
                 );

Verify that the DELETE performed correctly:

SELECT a.ITEM_NUMBER,
    a.CHARACTERISTIC,
    a.INTVALUE,
    a.FLOATVALUE,
    a.STRINGVALUE, COUNT(*)--MIN(RowID) AS RowID
FROM dbo.DUPPEDTABLE a WITH (NOLOCK)
GROUP BY a.ITEM_NUMBER,
    a.CHARACTERISTIC,
    a.INTVALUE,
    a.FLOATVALUE,
    a.STRINGVALUE
ORDER BY COUNT(*) DESC 

The result should have no rows with a count greater than 1. Finally, remove the rowid column:

ALTER TABLE dbo.DUPPEDTABLE DROP COLUMN RowID;

How to select rows in a DataFrame between two values, in Python Pandas?

Consider also series between:

df = df[df['closing_price'].between(99, 101)]

HTTP Error 500.19 and error code : 0x80070021

Got precisely the same error and came to this question. As @SpaceBison mentioned in comments, this answer describes the solution - https://stackoverflow.com/a/12867753/404099. I spotted it too late and it misses some steps. This is what worked for me:

Windows Server 2012, IIS 8.5. Should work for other versions too.

  • Go to server manager, click add roles and features
  • In the roles section choose: Web Server
    • Under Security sub-section choose everything (I excluded digest, IP restrictions and URL authorization as we don't use them)
    • Under Application Development choose .NET Extensibility 4.5, ASP.NET 4.5 and both ISAPI entries
  • In the features section choose: NET 3.5, .NET 4.5, ASP.NET 4.5
  • In the web server section choose: Web Server (all), Management Tools (IIS Management Console and Management Service), Windows Authentication - if you are using any of it

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Simplest way to detect a mobile device in PHP

I wrote this script to detect a mobile browser in PHP.

The code detects a user based on the user-agent string by preg_match()ing words that are found in only mobile devices user-agent strings after hundreds of tests. It has 100% accuracy on all current mobile devices and I'm currently updating it to support more mobile devices as they come out. The code is called isMobile and is as follows:

function isMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

You can use it like this:

// Use the function
if(isMobile()){
    // Do something for only mobile users
}
else {
    // Do something for only desktop users
}

To redirect a user to your mobile site, I would do this:

// Create the function, so you can use it
function isMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}
// If the user is on a mobile device, redirect them
if(isMobile()){
    header("Location: http://m.yoursite.com/");
}

Let me know if you have any questions and good luck!

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

How to increase buffer size in Oracle SQL Developer to view all records?

You can also edit the preferences file by hand to set the Array Fetch Size to any value.

Mine is found at C:\Users\<user>\AppData\Roaming\SQL Developer\system4.0.2.15.21\o.sqldeveloper.12.2.0.15.21\product-preferences.xml on Win 7 (x64).

The value is on line 372 for me and reads <value n="ARRAYFETCHSIZE" v="200"/>

I have changed it to 2000 and it works for me.

I had to restart SQL Developer.

How to find Port number of IP address?

DNS server usually have a standard of ports used. But if it's different, you could try nmap and do a port scan like so:

> nmap 127.0.0.1

Alternate table row color using CSS?

Most of the above codes won't work with IE version. The solution that works for IE+ other browsers is this.

   <style type="text/css">
      tr:nth-child(2n) {
             background-color: #FFEBCD;
        }
</style>

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

from list of integers, get number closest to a given value

>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4

A lambda is a special way of writing an "anonymous" function (a function that doesn't have a name). You can assign it any name you want because a lambda is an expression.

The "long" way of writing the the above would be:

def takeClosest(num,collection):
   return min(collection,key=lambda x:abs(x-num))

Shell script : How to cut part of a string

Assuming input of

{Anything}id={ID}{space}{Anything} 
{Anything}id={ID}{space}{Anything}

--

#! /bin/sh
while read s; do
   rhs=${s##*id=}
   id=${rhs%% *}
   echo $id # Do what you will with $id here
done <so.txt 

Or if it's always the 7th field

#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt

See Also

Shell Parameter Expansion

What is the ultimate postal code and zip regex?

We use the following:

Canada

([A-Z]{1}[0-9]{1}){3}   //We raise to upper first

America

[0-9]{5}                //-or-
[0-9]{5}-[0-9]{4}       //10 digit zip

Other

Accept as is

How to execute command stored in a variable?

Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash manpage):

  • initial word splitting
  • brace expansion
  • tilde expansion
  • parameter, variable and arithmetic expansion
  • command substitution
  • secondary word splitting
  • path expansion (aka globbing)
  • quote removal

Using $cmd directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.

Using eval "$cmd" does nothing until the quote removal phase, where $cmd is returned as is, and passed as a parameter to eval, whose function is to run the whole chain again before executing.

So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:

$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz

What is the best open source help ticket system?

Howabout Bugzilla. Open source and what Mozilla uses.

Detect if page has finished loading

One option is to have the page be blank, containing a small amount of javascript. Use the script to make an AJAX call to get the actual page content, and have the success function write the result over the current document. In the timeout function you can "do something else amazing"

Approximate pseudocode:

$(document).ready(function(){
    $.ajax
      url of actual page
      success:do something amazing
      timeout: do something else
});

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

IIS7 Cache-Control

That's not true Jeff.

You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.

Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.

You can, of course, achieve the same by providing web.config entries (or files) as needed.

Edit: removed a confusing sentence :)

How to pipe list of files returned by find command to cat to view all the files

To list and see contents of all abc.def files on a server in the directories /ghi and /jkl

find /ghi /jkl -type f -name abc.def 2> /dev/null -exec ls {} \; -exec cat {} \;

To list the abc.def files which have commented entries and display see those entries in the directories /ghi and /jkl

find /ghi /jkl -type f -name abc.def 2> /dev/null -exec grep -H ^# {} \;

Django Admin - change header 'Django administration' text

Update: If you are using Django 1.7+, see the answer below.


Original answer from 2011: You need to create your own admin base_site.html template to do this. The easiest way is to create the file:

/<projectdir>/templates/admin/base_site.html

This should be a copy of the original base_site.html, except putting in your custom title:

{% block branding %}
<h1 id="site-name">{% trans 'my cool admin console' %}</h1>
{% endblock %}

For this to work, you need to have the correct settings for your project, namely in settings.py:

  • Make sure /projectdir/templates/ is added into TEMPLATE_DIRS.
  • Make sure django.template.loaders.filesystem.Loader is added into TEMPLATE_LOADERS.

See docs for more information on settings.py.

SQL Server using wildcard within IN

In Access SQL, I would use this. I'd imagine that SQLserver has the same syntax.

select * from jobdetails where job_no like "0711*" or job_no like "0712*"

How to fill in proxy information in cntlm config file?

Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"

e.g pip install --proxy=localhost:3128 matplotlib

Visit this link to see full details.

CSS strikethrough different color from text?

Adding to @gojomo you could use :after pseudo element for the additional element. The only caveat is that you'll need to define your innerText in a data-text attribute since CSS has limited content functions.

_x000D_
_x000D_
s {_x000D_
  color: red;_x000D_
  text-align: -1000em;_x000D_
  overflow: hidden;_x000D_
}_x000D_
s:after {_x000D_
  color: black;_x000D_
  content: attr(data-text);_x000D_
}
_x000D_
<s data-text="Strikethrough">Strikethrough</s>
_x000D_
_x000D_
_x000D_

How to convert object array to string array in Java

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.

If you know your Object array contains Strings only, you may also do (instread of calling toString()):

for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];

The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:

    Object[] o = new String[10];
    String[] s = (String[]) o;

Print a string as hex bytes?

A bit more general for those who don't care about Python3 or colons:

from codecs import encode

data = open('/dev/urandom', 'rb').read(20)
print(encode(data, 'hex'))      # data

print(encode(b"hello", 'hex'))  # string

How to get past the login page with Wget?

I had the same problem. My solution was to do the login via Chrome and save the cookies data to a text file. This is easily done with this Chrome extension: Chrome cookie.txt export extension.

When you get the cookies data, there is also an example on how to use them with wget. A simple copy-paste command line is provided to you.

jQuery AJAX submit form

If you're using form.serialize() - you need to give each form element a name like this:

<input id="firstName" name="firstName" ...

And the form gets serialized like this:

firstName=Chris&lastName=Halcrow ...

Vertical Align Center in Bootstrap 4

I've tried all the answers herefrom, but found out here is the difference between h-100 and vh-100 Here is my solution:

      <div className='container vh-100 d-flex align-items-center col justify-content-center'>
        <div className="">
             ...
        </div>
      </div >

How do AX, AH, AL map onto EAX?

no your ans is Wrong

Selection of Al and Ah is from AX not from EAX

e.g

EAX=0000 0000 0000 0000 0000 0000 0000 0111

So if we call AX it should return

0000 0000 0000 0111

if we call AH it should return

0000 0000

and when we call AL it should return

0000 0111

Example number 2

EAX: 22 33 55 77
AX: 55 77
AH: 55    
AL: 77

example 3

EAX: 1111 0000 0000 0000 0000 0000 0000 0111    
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111  

Linq select to new object

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   

C# DataTable.Select() - How do I format the filter criteria to include null?

Try out Following:

DataRow rows = DataTable.Select("[Name]<>'n/a'")

For Null check in This:

DataRow rows =  DataTable.Select("[Name] <> 'n/a' OR [Name] is NULL" )

Google Play Services Library update and missing symbol @integer/google_play_services_version

Please note that this fix may only apply to IntelliJ users!! (More information at the bottom of this post that should apply to everyone.)

Fixed this problem! I use IntelliJ and it turns out I just had misconfigured the way I was including the google-play-services_lib module as a dependency.

As I fixed this entirely through GUI and not at all by editing any files, here's a couple of screenshots:

Step 1 - Initial Project Structure So my Project Structure started off looking like this...

Step 2 - Removed google-play-services library Then I removed the google-play-services library from my dependencies list by selecting it and then clicking the minus button at the bottom. Notice the error at the bottom of the dialog, as my project absolutely does require this library. But don't worry, we'll re-add it soon!

Step 3 - Added google-play-services as a module dependency Next I added google-play-services_lib as a module dependency instead of a library dependency. Then I hit the up arrow button at the bottom a couple times to move this dependency to the top of the list. But notice the error at the bottom (we're still not done yet!)

Step 4 - Click the lightbulb to add the google-play-services library as a dependency I then clicked the lightbulb at the bottom of the dialog in the error message area to bring up this little small popup that gives two choices (Add to dependencies... or Remove Library). Click the Add to dependencies... option!

Step 5 - Add the library to the google-play-services_lib module A new small dialog window should have popped up. It gave me two choices, one for my main project (it's name is blurred out), and then another for the google-play-services_lib project. Yours may have a bunch more depending on your project (like you may see actionbarsherlock, stuff like that). Select google-play-services_lib and click okay!

And finally, you're done! I hope this helps someone else out there!

Further info

I believe the reason that this issue was happening to begin with is because I thought that I had properly included the entire google-play-services_lib project into my overall project... but I actually had not, and had instead only properly included its jar file (google-play-services_lib/libs/google-play-services.jar). That jar file only includes code, not Android resources values, and so as such the @integer/google_play_services_version value was never really in my project. But the code was able to be used in my project, and so that made it seem like everything was fine.

And as a side note, fixing this issue also seems to have fixed the GooglePlayServicesUtil.getErrorDialog(...).show() crash that I used to have. But that could also have been fixed by the update, not really 100% sure there.

How do I properly compare strings in C?

Use strcmp.

This is in string.h library, and is very popular. strcmp return 0 if the strings are equal. See this for an better explanation of what strcmp returns.

Basically, you have to do:

while (strcmp(check,input) != 0)

or

while (!strcmp(check,input))

or

while (strcmp(check,input))

You can check this, a tutorial on strcmp.

CSS disable hover effect

From your question all I can understand is that you already have some hover effect on your button which you want remove. For that either remove that css which causes the hover effect or override it.

For overriding, do this

.buttonDisabled:hover
{
    //overriding css goes here
}

For example if your button's background color changes on hover from red to blue. In the overriding css you will make it as red so that it doesnt change.

Also go through all the rules of writing and overriding css. Get familiar with what css will have what priority.

Best of luck.

Read/Write 'Extended' file properties (C#)

For those of not crazy about VB, here it is in c#:

Note, you have to add a reference to Microsoft Shell Controls and Automation from the COM tab of the References dialog.

public static void Main(string[] args)
{
    List<string> arrHeaders = new List<string>();

    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder objFolder;

    objFolder = shell.NameSpace(@"C:\temp\testprop");

    for( int i = 0; i < short.MaxValue; i++ )
    {
        string header = objFolder.GetDetailsOf(null, i);
        if (String.IsNullOrEmpty(header))
            break;
        arrHeaders.Add(header);
    }

    foreach(Shell32.FolderItem2 item in objFolder.Items())
    {
        for (int i = 0; i < arrHeaders.Count; i++)
        {
            Console.WriteLine(
              $"{i}\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}");
        }
    }
}

How to set python variables to true or false?

you have to use capital True and False not true and false

Object creation on the stack/heap?

C++ offers three different ways to create objects:

  1. Stack-based such as temporary objects
  2. Heap-based by using new
  3. Static memory allocation such as global variables and namespace-scope objects

Consider your case,

Object* o;
o = new Object();

and:

Object* o = new Object();

Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.

pip install returning invalid syntax

You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)

How to rename array keys in PHP?

Recursive php rename keys function:

function replaceKeys($oldKey, $newKey, array $input){
    $return = array(); 
    foreach ($input as $key => $value) {
        if ($key===$oldKey)
            $key = $newKey;

        if (is_array($value))
            $value = replaceKeys( $oldKey, $newKey, $value);

        $return[$key] = $value;
    }
    return $return; 
}

How do I get values from a SQL database into textboxes using C#?

read = com.ExecuteReader()

SqlDataReader has a function Read() that reads the next row from your query's results and returns a bool whether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read() got). Or preferably make a loop while(read.Read()) if your query returns multiple rows.

How do I convert this list of dictionaries to a csv file?

Because @User and @BiXiC asked for help with UTF-8 here a variation of the solution by @Matthew. (I'm not allowed to comment, so I'm answering.)

import unicodecsv as csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

Include another JSP file

For a reason I don't yet understand, after I used <%@include file="includes/footer.jsp" %> in my index.jsp then in the other jsp files like register.jsp I had to use <%@ include file="footer.jsp"%>. As you see there was no more need to use full path, STS had store my initial path.

A beginner's guide to SQL database design

I started out with this article

http://en.tekstenuitleg.net/articles/software/database-design-tutorial/intro.html

It's pretty concise compared to reading an entire book and it explains the basics of database design (normalization, types of relationships) very well.

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

How to merge remote master to local branch

I found out it was:

$ git fetch upstream
$ git merge upstream/master

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Bash: Syntax error: redirection unexpected

Docker:

I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.

Note

To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]

Solution:

RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)"]

Notice the quotes around each parameter.

Trigger 404 in Spring-MVC controller?

I would like to mention that there's exception (not only) for 404 by default provided by Spring. See Spring documentation for details. So if you do not need your own exception you can simply do this:

 @RequestMapping(value = "/**", method = RequestMethod.GET)
 public ModelAndView show() throws NoSuchRequestHandlingMethodException {
    if(something == null)
         throw new NoSuchRequestHandlingMethodException("show", YourClass.class);

    ...

  }

Angularjs autocomplete from $http

You need to write a controller with ng-change function in scope. In ng-change callback you do a call to server and update completions. Here is a stub (without $http as this is a plunk):

HTML

<!doctype html>
<html ng-app="plunker">
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
        <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.4.0.js"></script>
        <script src="example.js"></script>
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
    </head>
    <body>
        <div class='container-fluid' ng-controller="TypeaheadCtrl">
            <pre>Model: {{selected| json}}</pre>
            <pre>{{states}}</pre>
            <input type="text" ng-change="onedit()" ng-model="selected" typeahead="state for state in states | filter:$viewValue">
        </div>
    </body>
</html>

JS

angular.module('plunker', ['ui.bootstrap']);

function TypeaheadCtrl($scope) {
  $scope.selected = undefined;
  $scope.states = [];

  $scope.onedit = function(){
    $scope.states = [];

    for(var i = 0; i < Math.floor((Math.random()*10)+1); i++){
      var value = "";

      for(var j = 0; j < i; j++){
        value += j;
      }
      $scope.states.push(value);
    }
  }
}

Copying HTML code in Google Chrome's inspect element

using httrack software you can download all the website content in your local. httrack : http://www.httrack.com/

How can I convert ArrayList<Object> to ArrayList<String>?

If you want to do it the dirty way, try this.

@SuppressWarnings("unchecked")
public ArrayList<String> convert(ArrayList<Object> a) {
   return (ArrayList) a;
}

Advantage: here you save time by not iterating over all objects.

Disadvantage: may produce a hole in your foot.

Refreshing data in RecyclerView and keeping its scroll position

EDIT: To restore the exact same apparent position, as in, make it look exactly like it did, we need to do something a bit different (See below how to restore the exact scrollY value):

Save the position and offset like this:

LinearLayoutManager manager = (LinearLayoutManager) mRecycler.getLayoutManager();
int firstItem = manager.findFirstVisibleItemPosition();
View firstItemView = manager.findViewByPosition(firstItem);
float topOffset = firstItemView.getTop();

outState.putInt(ARGS_SCROLL_POS, firstItem);
outState.putFloat(ARGS_SCROLL_OFFSET, topOffset);

And then restore the scroll like this:

LinearLayoutManager manager = (LinearLayoutManager) mRecycler.getLayoutManager();
manager.scrollToPositionWithOffset(mStatePos, (int) mStateOffset);

This restores the list to its exact apparent position. Apparent because it will look the same to the user, but it will not have the same scrollY value (because of possible differences in landscape/portrait layout dimensions).

Note that this only works with LinearLayoutManager.

--- Below how to restore the exact scrollY, which will likely make the list look different ---

  1. Apply an OnScrollListener like so:

    private int mScrollY;
    private RecyclerView.OnScrollListener mTotalScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mScrollY += dy;
        }
    };
    

This will store the exact scroll position at all times in mScrollY.

  1. Store this variable in your Bundle, and restore it in state restoration to a different variable, we'll call it mStateScrollY.

  2. After state restoration and after your RecyclerView has reset all its data reset the scroll with this:

    mRecyclerView.scrollBy(0, mStateScrollY);
    

That's it.

Beware, that you restore the scroll to a different variable, this is important, because the OnScrollListener will be called with .scrollBy() and subsequently will set mScrollY to the value stored in mStateScrollY. If you do not do this mScrollY will have double the scroll value (because the OnScrollListener works with deltas, not absolute scrolls).

State saving in activities can be achieved like this:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(ARGS_SCROLL_Y, mScrollY);
}

And to restore call this in your onCreate():

if(savedState != null){
    mStateScrollY = savedState.getInt(ARGS_SCROLL_Y, 0);
}

State saving in fragments works in a similar way, but the actual state saving needs a bit of extra work, but there are plenty of articles dealing with that, so you shouldn't have a problem finding out how, the principles of saving the scrollY and restoring it remain the same.

Use own username/password with git and bitbucket

Run

git remote -v

and check whether your origin's URL has your co-worker's username hardcoded in there. If so, substitute it with your own:

git remote set-url origin <url-with-your-username>

Remove #N/A in vlookup result

if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.

Check if one date is between two dates

Here is a Date Prototype method written in typescript:

Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
  if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
  return !minDate ? true : this.getTime() >= minDate.getTime()
    && !maxDate ? true : this.getTime() <= maxDate.getTime();
};

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

I made the steps 1, 2, 3 and the 7. and I put the folder with the class files in the project build path (right click, properties, java build path, libraries, add class folder, create new folder, advanced>>, link to folder in the file system, browse,...) then restart eclipse.

From ND to 1D arrays

Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.

def getVector(data_array,col):
    vector = []
    imax = len(data_array)
    for i in range(imax):
        vector.append(data_array[i][col])
    return ( vector )
a = ([1,2,3], [4,5,6])
b = getVector(a,1)
print(b)

Out>[2,5]

So if you need to transpose, you can do something like this:

def transposeArray(data_array):
    # need to test if this is a 1D array 
    # can't do a len(data_array[0]) if it's 1D
    two_d = True
    if isinstance(data_array[0], list):
        dimx = len(data_array[0])
    else:
        dimx = 1
        two_d = False
    dimy = len(data_array)
    # init output transposed array
    data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
    # fill output transposed array
    for i in range(dimx):
        for j in range(dimy):
            if two_d:
                data_array_t[j][i] = data_array[i][j]
            else:
                data_array_t[j][i] = data_array[j]
    return data_array_t

Getting the encoding of a Postgres database

Method 1:

If you're already logged in to the db server, just copy and paste this.

SHOW SERVER_ENCODING;

Result:

  server_encoding 
-----------------  
UTF8

For Client encoding :

 SHOW CLIENT_ENCODING;

Method 2:

Again if you are already logged in, use this to get the list based result

\l 

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

How can I get a user's media from Instagram without authenticating as a user?

This works using a simple ajax call and iterating image paths.

        var name = "nasa";
        $.get("https://www.instagram.com/" + name + "/?__a=1", function (data, status) {
            console.log('IG_NODES', data.user.media.nodes);
            $.each(data.user.media.nodes, function (n, item) {
                console.log('ITEMS', item.display_src);
                $('body').append(
                    "<div class='col-md-4'><img class='img-fluid d-block' src='" + item.display_src + "'></div>"
                );
            });
        })

simple HTTP server in Java using only Java SE API

This code is better than ours, you only need to add 2 libs: javax.servelet.jar and org.mortbay.jetty.jar.

Class Jetty:

package jetty;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.mortbay.http.SocketListener;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHttpContext;

public class Jetty {

    public static void main(String[] args) {
        try {
            Server server = new Server();
            SocketListener listener = new SocketListener();      

            System.out.println("Max Thread :" + listener.getMaxThreads() + " Min Thread :" + listener.getMinThreads());

            listener.setHost("localhost");
            listener.setPort(8070);
            listener.setMinThreads(5);
            listener.setMaxThreads(250);
            server.addListener(listener);            

            ServletHttpContext context = (ServletHttpContext) server.getContext("/");
            context.addServlet("/MO", "jetty.HelloWorldServlet");

            server.start();
            server.join();

        /*//We will create our server running at http://localhost:8070
        Server server = new Server();
        server.addListener(":8070");

        //We will deploy our servlet to the server at the path '/'
        //it will be available at http://localhost:8070
        ServletHttpContext context = (ServletHttpContext) server.getContext("/");
        context.addServlet("/MO", "jetty.HelloWorldServlet");

        server.start();
        */

        } catch (Exception ex) {
            Logger.getLogger(Jetty.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
} 

Servlet class:

package jetty;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
    {
        String appid = httpServletRequest.getParameter("appid");
        String conta = httpServletRequest.getParameter("conta");

        System.out.println("Appid : "+appid);
        System.out.println("Conta : "+conta);

        httpServletResponse.setContentType("text/plain");
        PrintWriter out = httpServletResponse.getWriter();
        out.println("Hello World!");
        out.close();
    }
}

Fastest check if row exists in PostgreSQL

Use the EXISTS key word for TRUE / FALSE return:

select exists(select 1 from contact where id=12)

Vertically align text within input field of fixed-height without display: table or padding?

I've not tried this myself, but try setting:

height : 36px; //for other browsers
line-height: 36px; // for IE

Where 36px is the height of your input.

Is there a way to get version from package.json in nodejs code?

Option 1

Best practice is to version from package.json using npm environment variables.

process.env.npm_package_version

more information on: https://docs.npmjs.com/using-npm/config.html

This will work only when you start your service using NPM command.

Quick Info: you can read any values in pacakge.json using process.env.npm_package_[keyname]

Option 2

Setting version in environment variable using https://www.npmjs.com/package/dotenv as .env file and reading it as process.env.version

How to send push notification to web browser?

May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

Case objects vs Enumerations in Scala

UPDATE: A new macro based solution has been created which is far superior to the solution I outline below. I strongly recommend using this new macro based solution. And it appears plans for Dotty will make this style of enum solution part of the language. Whoohoo!

Summary:
There are three basic patterns for attempting to reproduce the Java Enum within a Scala project. Two of the three patterns; directly using Java Enum and scala.Enumeration, are not capable of enabling Scala's exhaustive pattern matching. And the third one; "sealed trait + case object", does...but has JVM class/object initialization complications resulting in inconsistent ordinal index generation.

I have created a solution with two classes; Enumeration and EnumerationDecorated, located in this Gist. I didn't post the code into this thread as the file for Enumeration was quite large (+400 lines - contains lots of comments explaining implementation context).

Details:
The question you're asking is pretty general; "...when to use caseclassesobjects vs extending [scala.]Enumeration". And it turns out there are MANY possible answers, each answer depending on the subtleties of the specific project requirements you have. The answer can be reduced down to three basic patterns.

To start, let's make sure we are working from the same basic idea of what an enumeration is. Let's define an enumeration mostly in terms of the Enum provided as of Java 5 (1.5):

  1. It contains a naturally ordered closed set of named members
    1. There is a fixed number of members
    2. Members are naturally ordered and explicitly indexed
      • As opposed to being sorted based on some inate member queriable criteria
    3. Each member has a unique name within the total set of all members
  2. All members can easily be iterated through based on their indexes
  3. A member can be retrieved with its (case sensitive) name
    1. It would be quite nice if a member could also be retrieved with its case insensitive name
  4. A member can be retrieved with its index
  5. Members may easily, transparently and efficiently use serialization
  6. Members may be easily extended to hold additional associated singleton-ness data
  7. Thinking beyond Java's Enum, it would be nice to be able to explicitly leverage Scala's pattern matching exhaustiveness checking for an enumeration

Next, let's look at boiled down versions of the three most common solution patterns posted:

A) Actually directly using Java Enum pattern (in a mixed Scala/Java project):

public enum ChessPiece {
    KING('K', 0)
  , QUEEN('Q', 9)
  , BISHOP('B', 3)
  , KNIGHT('N', 3)
  , ROOK('R', 5)
  , PAWN('P', 1)
  ;

  private char character;
  private int pointValue;

  private ChessPiece(char character, int pointValue) {
    this.character = character; 
    this.pointValue = pointValue;   
  }

  public int getCharacter() {
    return character;
  }

  public int getPointValue() {
    return pointValue;
  }
}

The following items from the enumeration definition are not available:

  1. 3.1 - It would be quite nice if a member could also be retrieved with its case insensitive name
  2. 7 - Thinking beyond Java's Enum, it would be nice to be able to explicitly leverage Scala's pattern matching exhaustiveness checking for an enumeration

For my current projects, I don't have the benefit of taking the risks around the Scala/Java mixed project pathway. And even if I could choose to do a mixed project, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.


B) Using the "sealed trait + case objects" pattern:

sealed trait ChessPiece {def character: Char; def pointValue: Int}
object ChessPiece {
  case object KING extends ChessPiece {val character = 'K'; val pointValue = 0}
  case object QUEEN extends ChessPiece {val character = 'Q'; val pointValue = 9}
  case object BISHOP extends ChessPiece {val character = 'B'; val pointValue = 3}
  case object KNIGHT extends ChessPiece {val character = 'N'; val pointValue = 3}
  case object ROOK extends ChessPiece {val character = 'R'; val pointValue = 5}
  case object PAWN extends ChessPiece {val character = 'P'; val pointValue = 1}
}

The following items from the enumeration definition are not available:

  1. 1.2 - Members are naturally ordered and explicitly indexed
  2. 2 - All members can easily be iterated through based on their indexes
  3. 3 - A member can be retrieved with its (case sensitive) name
  4. 3.1 - It would be quite nice if a member could also be retrieved with its case insensitive name
  5. 4 - A member can be retrieved with its index

It's arguable it really meets enumeration definition items 5 and 6. For 5, it's a stretch to claim it's efficient. For 6, it's not really easy to extend to hold additional associated singleton-ness data.


C) Using the scala.Enumeration pattern (inspired by this StackOverflow answer):

object ChessPiece extends Enumeration {
  val KING = ChessPieceVal('K', 0)
  val QUEEN = ChessPieceVal('Q', 9)
  val BISHOP = ChessPieceVal('B', 3)
  val KNIGHT = ChessPieceVal('N', 3)
  val ROOK = ChessPieceVal('R', 5)
  val PAWN = ChessPieceVal('P', 1)
  protected case class ChessPieceVal(character: Char, pointValue: Int) extends super.Val()
  implicit def convert(value: Value) = value.asInstanceOf[ChessPieceVal]
}

The following items from the enumeration definition are not available (happens to be identical to the list for directly using the Java Enum):

  1. 3.1 - It would be quite nice if a member could also be retrieved with its case insensitive name
  2. 7 - Thinking beyond Java's Enum, it would be nice to be able to explicitly leverage Scala's pattern matching exhaustiveness checking for an enumeration

Again for my current projects, item 7 is critical for allowing me to catch compile time issues if/when I either add/remove enumeration members, or am writing some new code to deal with existing enumeration members.


So, given the above definition of an enumeration, none of the above three solutions work as they do not provide everything outlined in the enumeration definition above:

  1. Java Enum directly in a mixed Scala/Java project
  2. "sealed trait + case objects"
  3. scala.Enumeration

Each of these solutions can be eventually reworked/expanded/refactored to attempt to cover some of each one's missing requirements. However, neither the Java Enum nor the scala.Enumeration solutions can be sufficiently expanded to provide item 7. And for my own projects, this is one of the more compelling values of using a closed type within Scala. I strongly prefer compile time warnings/errors to indicate I have a gap/issue in my code as opposed to having to glean it out of a production runtime exception/failure.


In that regard, I set about working with the case object pathway to see if I could produce a solution which covered all of the enumeration definition above. The first challenge was to push through the core of the JVM class/object initialization issue (covered in detail in this StackOverflow post). And I was finally able to figure out a solution.

As my solution is two traits; Enumeration and EnumerationDecorated, and since the Enumeration trait is over +400 lines long (lots of comments explaining context), I am forgoing pasting it into this thread (which would make it stretch down the page considerbly). For details, please jump directly to the Gist.

Here's what the solution ends up looking like using the same data idea as above (fully commented version available here) and implemented in EnumerationDecorated.

import scala.reflect.runtime.universe.{TypeTag,typeTag}
import org.public_domain.scala.utils.EnumerationDecorated

object ChessPiecesEnhancedDecorated extends EnumerationDecorated {
  case object KING extends Member
  case object QUEEN extends Member
  case object BISHOP extends Member
  case object KNIGHT extends Member
  case object ROOK extends Member
  case object PAWN extends Member

  val decorationOrderedSet: List[Decoration] =
    List(
        Decoration(KING,   'K', 0)
      , Decoration(QUEEN,  'Q', 9)
      , Decoration(BISHOP, 'B', 3)
      , Decoration(KNIGHT, 'N', 3)
      , Decoration(ROOK,   'R', 5)
      , Decoration(PAWN,   'P', 1)
    )

  final case class Decoration private[ChessPiecesEnhancedDecorated] (member: Member, char: Char, pointValue: Int) extends DecorationBase {
    val description: String = member.name.toLowerCase.capitalize
  }
  override def typeTagMember: TypeTag[_] = typeTag[Member]
  sealed trait Member extends MemberDecorated
}

This is an example usage of a new pair of enumeration traits I created (located in this Gist) to implement all of the capabilities desired and outlined in the enumeration definition.

One concern expressed is that the enumeration member names must be repeated (decorationOrderedSet in the example above). While I did minimize it down to a single repetition, I couldn't see how to make it even less due to two issues:

  1. JVM object/class initialization for this particular object/case object model is undefined (see this Stackoverflow thread)
  2. The content returned from the method getClass.getDeclaredClasses has an undefined order (and it is quite unlikely to be in the same order as the case object declarations in the source code)

Given these two issues, I had to give up trying to generate an implied ordering and had to explicitly require the client define and declare it with some sort of ordered set notion. As the Scala collections do not have an insert ordered set implementation, the best I could do was use a List and then runtime check that it was truly a set. It's not how I would have preferred to have achieved this.

And given the design required this second list/set ordering val, given the ChessPiecesEnhancedDecorated example above, it was possible to add case object PAWN2 extends Member and then forget to add Decoration(PAWN2,'P2', 2) to decorationOrderedSet. So, there is a runtime check to verify that the list is not only a set, but contains ALL of the case objects which extend the sealed trait Member. That was a special form of reflection/macro hell to work through.


Please leave comments and/or feedback on the Gist.

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Simple regular expression for a decimal with a precision of 2

Won't you need to take the e in e666.76 into account?

With

(e|0-9)\d*\d.\d{1,2)

Working with INTERVAL and CURDATE in MySQL

As suggested by A Star, I always use something along the lines of:

DATE(NOW()) - INTERVAL 1 MONTH

Similarly you can do:

NOW() + INTERVAL 5 MINUTE
"2013-01-01 00:00:00" + INTERVAL 10 DAY

and so on. Much easier than typing DATE_ADD or DATE_SUB all the time :)!

PHPMailer AddAddress()

All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:

See it in action with jsfiddle here (except the php processor)

### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
    var nextEmail, inside_where;
    nextEmail = document.createElement('input');
    nextEmail.type = 'text';
    nextEmail.name = 'emails[]';
    nextEmail.className = 'class_for_styling';
    nextEmail.style.display = 'block';
    nextEmail.placeholder  = 'Enter E-mail Here';
    inside_where = document.getElementById('addEmail');
    inside_where.appendChild(nextEmail);
    return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
    foreach ($_POST[emails] AS $postEmail){
        if ($postEmail){$mailer->AddAddress($postEmail);}
    }
} 
?>

So what it does basically is to generate a new input text box on every click with the name "emails[]".

The [] added at the end makes it an array when posted.

Then we go through each element of the array with "foreach" on PHP side adding the:

    $mailer->AddAddress($postEmail);

Why and when to use angular.copy? (Deep Copy)

When using angular.copy, instead of updating the reference, a new object is created and assigned to the destination(if a destination is provided). But there's more. There's this cool thing that happens after a deep copy.

Say you have a factory service which has methods which updates factory variables.

angular.module('test').factory('TestService', [function () {
    var o = {
        shallow: [0,1], // initial value(for demonstration)
        deep: [0,2] // initial value(for demonstration)
    }; 
    o.shallowCopy = function () {
        o.shallow = [1,2,3]
    }
    o.deepCopy = function () {
        angular.copy([4,5,6], o.deep);
    }
    return o;
}]);

and a controller which uses this service,

angular.module('test').controller('Ctrl', ['TestService', function (TestService) {
     var shallow = TestService.shallow;
     var deep = TestService.deep;

     console.log('****Printing initial values');
     console.log(shallow);
     console.log(deep);

     TestService.shallowCopy();
     TestService.deepCopy();

     console.log('****Printing values after service method execution');
     console.log(shallow);
     console.log(deep);

     console.log('****Printing service variables directly');
     console.log(TestService.shallow);
     console.log(TestService.deep);
}]);

When the above program is run the output will be as follows,

****Printing initial values
[0,1]
[0,2]

****Printing values after service method execution
[0,1]
[4,5,6]

****Printing service variables directly
[1,2,3]
[4,5,6]

Thus the cool thing about using angular copy is that, the references of the destination are reflected with the change of values, without having to re-assign the values manually, again.

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

Is there a MySQL option/feature to track history of changes to records?

Here is how we solved it

a Users table looked like this

Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on

And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this

Users (the data that won't change over time)
-------------
id | name

UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
 1 |   1     |    0     | NY   | lake st | 9809  | @long | 2015-10-24 10:24:20
 2 |   1     |    2     | Tokyo| lake st | 9809  | @long | 2015-10-24 10:24:20
 3 |   1     |    3     | Sdny | lake st | 9809  | @long | 2015-10-24 10:24:20
 4 |   2     |    0     | Ankr | lake st | 9809  | @long | 2015-10-24 10:24:20
 5 |   2     |    1     | Lond | lake st | 9809  | @long | 2015-10-24 10:24:20

To find the current address of any user, we search for UserData with revision DESC and LIMIT 1

To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Storing data into list with class

One way(in one line) to do it is like this:

listemail.Add(new EmailData {FirstName = "John", LastName = "Smith", Location = "Los Angeles"});

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword can be interpreted in two different ways depending on what it's used on:

Value types: For ints, doubles etc, it will ensure that the value cannot change,

Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same.

As such, final List<Whatever> foo; ensures that foo always refers to the same list, but the contents of said list may change over time.

Sending JSON object to Web API

Try this:

jquery

    $('#save-source').click(function (e) {
        e.preventDefault();
        var source = {
            'ID': 0,
            //'ProductID': $('#ID').val(),
            'PartNumber': $('#part-number').val(),
            //'VendorID': $('#Vendors').val()
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/api/PartSourceAPI",
            data: source,
            success: function (data) {
                alert(data);
            },
            error: function (error) {
                jsonValue = jQuery.parseJSON(error.responseText);
                //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
            }
        });
    });

Controller

    public string Post(PartSourceModel model)
    {
        return model.PartNumber;
    }

View

<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />

<input type="submit" id="save-source" name="save-source" value="Add" />

Now when you click 'Add' after you fill out the text box, the controller will spit back out what you wrote in the PartNumber box in an alert.

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

How do I run Selenium in Xvfb?

This is the setup I use:

Before running the tests, execute:

export DISPLAY=:99
/etc/init.d/xvfb start

And after the tests:

/etc/init.d/xvfb stop

The init.d file I use looks like this:

#!/bin/bash

XVFB=/usr/bin/Xvfb
XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16"
PIDFILE=${HOME}/xvfb_${DISPLAY:1}.pid
case "$1" in
  start)
    echo -n "Starting virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
    echo "."
    ;;
  stop)
    echo -n "Stopping virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE
    echo "."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
  echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
  exit 1
esac
exit 0

Use string value from a cell to access worksheet of same name

You can use the formula INDIRECT().

This basically takes a string and treats it as a reference. In your case, you would use:

=INDIRECT("'"&A5&"'!G7")

The double quotes are to show that what's inside are strings, and only A5 here is a reference.

Conversion failed when converting from a character string to uniqueidentifier

this fails:

 DECLARE @vPortalUID NVARCHAR(32)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
 PRINT @nPortalUID

this works

 DECLARE @vPortalUID NVARCHAR(36)
 SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
 DECLARE @nPortalUID AS UNIQUEIDENTIFIER
 SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
 PRINT @nPortalUID

the difference is NVARCHAR(36), your input parameter is too small!

How to add parameters to an external data query in Excel which can't be displayed graphically?

Excel's interface for SQL Server queries will not let you have a custom parameters.  A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties.  Here are the detailed steps for Excel 2010:

  1. Open Excel
  2. Goto Data tab
  3. From the From Other Sources button choose From Microsoft Query
  4. The "Choose Data Source" window will appear.  Choose a datasource and click OK.
  5. The Query Qizard
    1. Choose Column: window will appear.  The goal is to create a generic query. I recommend choosing one column from a small table.
    2. Filter Data: Just click Next
    3. Sort Order: Just click Next
    4. Finish: Just click Finish.
  6. The "Import Data" window will appear:
    1. Click the Properties... button.
      1. Choose the Definition tab
      2. In the "Command text:" section add a WHERE clause that includes Excel parameters.  It's important to add all the parameters that you want now.  For example, if I want two parameters I could add this:
        WHERE 1 = ? and 2 = ?
      3. Click OK to get back to the "Import Data" window
    2. Choose PivotTable Report
    3. Click OK
  7. You will be prompted to enter the parameters value for each parameter.
  8. Once you have enter the parameters you will be at your pivot table
  9. Go batck to the Data tab and click the connections Properties button
    1. Click the Definition tab
    2. In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
    3. Click the Parameters... button 
      1. enter the Prompt values for each parameter
      2. Click OK
    4. Click OK to close the properties window
  10. Congratulations, you now have parameters.

Best database field type for a URL

Most web servers have a URL length limit (which is why there is an error code for "URI too long"), meaning there is a practical upper size. Find the default length limit for the most popular web servers, and use the largest of them as the field's maximum size; it should be more than enough.

How to press/click the button using Selenium if the button does not have the Id?

Use xpath selector (here's quick tutorial) instead of id:

#python:
from selenium.webdriver import Firefox

YOUR_PAGE_URL = 'http://mypage.com/'
NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'

browser = Firefox()
browser.get(YOUR_PAGE_URL)

button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

Or, if you use "vanilla" Selenium, just use same xpath selector instead of button id:

NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
selenium.click(NEXT_BUTTON_XPATH)

Redis - Connect to Remote Server

I was struggling with the remote connection to Redis for some days. Finally I made it. Here is the full check list I put together to follow to get connected. Some of solutions are given in the answers above. Yet I wanted my answer to be a nano-wiki on the subject:) I added some useful links too.

If redis works locally:

$ redis-cli
127.0.0.1:6379>ping
PONG
127.0.0.1:6379>

If the password is not set

See /etc/redis/redis.conf config (this is default locaion for Ubuntu 18.04, you may have it in the different location):

# The following line should be commented
# requirepass <some pass if any>

If the protected mode is set to 'no' in the config:

# The following line should be uncommented
protected-mode no

if the IP binding is open for an access from internet in the config:

# The following line should be commented
# bind 127.0.0.1 ::1

If the Linux firewall allows connections

(here for Ubuntu 18.04) Check it allows for incoming internet traffic to go to port 6379 (the Redis default port)

# To check if it the port is open
$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
...
6379/tcp                   ALLOW       Anywhere
6379/tcp (v6)              ALLOW       Anywhere (v6)
...

# To open the port
$ sudo ufw allow 6379/tcp

Restart Redis service

Do not forget to restart the Redis service for changes to take effect and see it is running:

$ sudo systemctl restart redis.service
$ sudo systemctl status redis

Check if it works as a remote server

from your command line use redis-cli as if Redis server were on the remote server:

$ redis-cli -h <your-server-ip>
<your-server-ip>:6379> ping
PONG
<your-server-ip>:6379> exit
$

If you can ping-PONG your Redis server via your internet server connected as a remote server than the remote Redis connection works.

Security Warning

All the above makes your Redis data to be completely open to anybody from the internet.

To basically secure Redis use requirepass and protected-mode yes settings in Redis config (see above) and block the dangerous Redis commands (see the link above), for a deeper understanding see this article and Redis site security section ).

Useful links

Some links to help How to install and secure Redis on Ubuntu 18.04 and how to setup Ubuntu 18.04 firewall.

Hope it helps.

MySQL Select all columns from one table and some from another table

Using alias for referencing the tables to get the columns from different tables after joining them.

Select tb1.*, tb2.col1, tb2.col2 from table1 tb1 JOIN table2 tb2 on tb1.Id = tb2.Id

How to Store Historical Data

Supporting historical data directly within an operational system will make your application much more complex than it would otherwise be. Generally, I would not recommend doing it unless you have a hard requirement to manipulate historical versions of a record within the system.

If you look closely, most requirements for historical data fall into one of two categories:

  • Audit logging: This is better off done with audit tables. It's fairly easy to write a tool that generates scripts to create audit log tables and triggers by reading metadata from the system data dictionary. This type of tool can be used to retrofit audit logging onto most systems. You can also use this subsystem for changed data capture if you want to implement a data warehouse (see below).

  • Historical reporting: Reporting on historical state, 'as-at' positions or analytical reporting over time. It may be possible to fulfil simple historical reporting requirements by quering audit logging tables of the sort described above. If you have more complex requirements then it may be more economical to implement a data mart for the reporting than to try and integrate history directly into the operational system.

    Slowly changing dimensions are by far the simplest mechanism for tracking and querying historical state and much of the history tracking can be automated. Generic handlers aren't that hard to write. Generally, historical reporting does not have to use up-to-the-minute data, so a batched refresh mechanism is normally fine. This keeps your core and reporting system architecture relatively simple.

If your requirements fall into one of these two categories, you are probably better off not storing historical data in your operational system. Separating the historical functionality into another subsystem will probably be less effort overall and produce transactional and audit/reporting databases that work much better for their intended purpose.

C++: How to round a double to an int?

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double x=54.999999999999943157;
    int y=ceil(x);//The ceil() function returns the smallest integer no less than x
    return 0;
}

Node.js - use of module.exports as a constructor

CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new keywords has a simple answer: Yes. I'll illustrate...

Module exports

You can either use the exports variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require() is a reference to the value of module.exports.

A pseudo-code example of how a module is defined:

var theModule = {
  exports: {}
};

(function(module, exports, require) {

  // Your module code goes here

})(theModule, theModule.exports, theRequireFunction);

In the example above module.exports and exports are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.

Require with constructors

Since you can attach a function directly to module.exports you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)

So the following is perfectly good code and I personally encourage it:

// My module
function MyObject(bar) {
  this.bar = bar;
}

MyObject.prototype.foo = function foo() {
  console.log(this.bar);
};

module.exports = MyObject;

// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"

Require for non-constructors

Same thing goes for non-constructor like functions:

// My Module
exports.someFunction = function someFunction(msg) {
  console.log(msg);
}

// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"

jQuery: checking if the value of a field is null (empty)

Try

_x000D_
_x000D_
if( this["person_data[document_type]"].value != '') { _x000D_
  console.log('not empty');_x000D_
}
_x000D_
<input id="person_data[document_type]" value="test" />
_x000D_
_x000D_
_x000D_

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

DECLARE @dayNumber INT;
SET @dayNumber = DATEPART(DW, GETDATE());

--Sunday = 1, Saturday = 7.
IF(@dayNumber = 1 OR @dayNumber = 7) 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

This may generate wrong results, because the number produced by the weekday datepart depends on the value set by SET DATEFIRST. This sets the first day of the week. So another way is:

DECLARE @dayName VARCHAR(9);
SET @dayName = DATEName(DW, GETDATE());

IF(@dayName = 'Saturday' OR @dayName = 'Sunday') 
    PRINT 'Weekend';
ELSE
    PRINT 'NOT Weekend';

How do I set session timeout of greater than 30 minutes

Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.

So

<session-config>
    <session-timeout>60</session-timeout>
</session-config>

sets the default session timeout to 60 minutes.

And

session.setMaxInactiveInterval(600);

sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.

This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.

Oracle: SQL query that returns rows with only numeric values

The complete list of the regexp_like and other regexp functions in Oracle 11.1:

http://66.221.222.85/reference/regexp.html

In your example:

SELECT X
FROM test
WHERE REGEXP_LIKE(X, '^[[:digit:]]$');

How do you push a Git tag to a branch using a refspec?

It is probably failing because 1.0.0 is an annotated tag. Perhaps you saw the following error message:

error: Trying to write non-commit object to branch refs/heads/master

Annotated tags have their own distinct type of object that points to the tagged commit object. Branches can not usefully point to tag objects, only commit objects. You need to “peel” the annotated tag back to commit object and push that instead.

git push production +1.0.0^{commit}:master
git push production +1.0.0~0:master          # shorthand

There is another syntax that would also work in this case, but it means something slightly different if the tag object points to something other than a commit (or a tag object that points to (a tag object that points to a …) a commit).

git push production +1.0.0^{}:master

These tag peeling syntaxes are described in git-rev-parse(1) under Specifying Revisions.

TCPDF ERROR: Some data has already been output, can't send PDF file

I had the same error but finally I solved it by suppressing PHP errors Just put this code error_reporting(0); at the top of your print page

    <?php 
    error_reporting(0); //hide php errors
    if( ! defined('BASEPATH')) exit('No direct script access allowed');
    require_once dirname(__FILE__) . '/tohtml/tcpdf/tcpdf.php';
    .... //continue

Writing String to Stream and reading it back does not work

After you write to the MemoryStream and before you read it back, you need to Seek back to the beginning of the MemoryStream so you're not reading from the end.

UPDATE

After seeing your update, I think there's a more reliable way to build the stream:

UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";

// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object    
using(MemoryStream ms = new MemoryStream())
{
    var sw = new StreamWriter(ms, uniEncoding);
    try
    {
        sw.Write(message);
        sw.Flush();//otherwise you are risking empty stream
        ms.Seek(0, SeekOrigin.Begin);

        // Test and work with the stream here. 
        // If you need to start back at the beginning, be sure to Seek again.
    }
    finally
    {
        sw.Dispose();
    }
}

As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream. This takes the hassle out of ensuring the entire byte array for the string is written.

Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.

What is the default value for enum variable?

You can use this snippet :-D

using System;
using System.Reflection;

public static class EnumUtils
{
    public static T GetDefaultValue<T>()
        where T : struct, Enum
    {
        return (T)GetDefaultValue(typeof(T));
    }

    public static object GetDefaultValue(Type enumType)
    {
        var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
        if (attribute != null)
            return attribute.Value;

        var innerType = enumType.GetEnumUnderlyingType();
        var zero = Activator.CreateInstance(innerType);
        if (enumType.IsEnumDefined(zero))
            return zero;

        var values = enumType.GetEnumValues();
        return values.GetValue(0);
    }
}

Example:

using System;

public enum Enum1
{
    Foo,
    Bar,
    Baz,
    Quux
}
public enum Enum2
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 0
}
public enum Enum3
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
    Foo  = 1,
    Bar  = 2,
    Baz  = 3,
    Quux = 4
}

public static class Program 
{
    public static void Main() 
    {
        var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
        Console.WriteLine(defaultValue1); // Foo

        var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
        Console.WriteLine(defaultValue2); // Quux

        var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
        Console.WriteLine(defaultValue3); // Foo

        var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
        Console.WriteLine(defaultValue4); // Bar
    }
}

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Convert IEnumerable to DataTable

Look at this one: Convert List/IEnumerable to DataTable/DataView

In my code I changed it into a extension method:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

How to Cast Objects in PHP

Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform one class to another with preassumption of the developer knows and understand the similarity of 2 classes.

There's no existing solution for transforming between objects. What you can try out are:

Sample random rows in dataframe

You could do this:

library(dplyr)

cols <- paste0("a", 1:10)
tab <- matrix(1:1000, nrow = 100) %>% as.tibble() %>% set_names(cols)
tab
# A tibble: 100 x 10
      a1    a2    a3    a4    a5    a6    a7    a8    a9   a10
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1     1   101   201   301   401   501   601   701   801   901
 2     2   102   202   302   402   502   602   702   802   902
 3     3   103   203   303   403   503   603   703   803   903
 4     4   104   204   304   404   504   604   704   804   904
 5     5   105   205   305   405   505   605   705   805   905
 6     6   106   206   306   406   506   606   706   806   906
 7     7   107   207   307   407   507   607   707   807   907
 8     8   108   208   308   408   508   608   708   808   908
 9     9   109   209   309   409   509   609   709   809   909
10    10   110   210   310   410   510   610   710   810   910
# ... with 90 more rows

Above I just made a dataframe with 10 columns and 100 rows, ok?

Now you can sample it with sample_n:

sample_n(tab, size = 800, replace = T)
# A tibble: 800 x 10
      a1    a2    a3    a4    a5    a6    a7    a8    a9   a10
   <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
 1    53   153   253   353   453   553   653   753   853   953
 2    14   114   214   314   414   514   614   714   814   914
 3    10   110   210   310   410   510   610   710   810   910
 4    70   170   270   370   470   570   670   770   870   970
 5    36   136   236   336   436   536   636   736   836   936
 6    77   177   277   377   477   577   677   777   877   977
 7    13   113   213   313   413   513   613   713   813   913
 8    58   158   258   358   458   558   658   758   858   958
 9    29   129   229   329   429   529   629   729   829   929
10     3   103   203   303   403   503   603   703   803   903
# ... with 790 more rows

notifyDataSetChanged example

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

Your choices are:

  1. Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
  2. Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
  3. Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
  4. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

Put byte array to JSON and vice versa

In line with @Qwertie's suggestion, but going further on the lazy side, you could just pretend that each byte is a ISO-8859-1 character. For the uninitiated, ISO-8859-1 is a single-byte encoding that matches the first 256 code points of Unicode.

So @Ash's answer is actually redeemable with a charset:

byte[] args2 = getByteArry();
String byteStr = new String(args2, Charset.forName("ISO-8859-1"));

This encoding has the same readability as BAIS, with the advantage that it is processed faster than either BAIS or base64 as less branching is required. It might look like the JSON parser is doing a bit more, but it's fine because dealing with non-ASCII by escaping or by UTF-8 is part of a JSON parser's job anyways. It could map better to some formats like MessagePack with a profile.

Space-wise however, it is usually a loss, as nobody would be using UTF-16 for JSON. With UTF-8 each non-ASCII byte would occupy 2 bytes, while BAIS uses (2+4n + r?(r+1):0) bytes for every run of 3n+r such bytes (r is the remainder).

How to encode URL to avoid special characters in Java?

Here is my solution which is pretty easy:

Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)

String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
    review = URLEncoder.encode(review,"utf-8");
    review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;

disable editing default value of text input

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form.

<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">

What is the difference between lower bound and tight bound?

If you have something that's O(f(n)) that means there's are k, g(n) such that f(n)k g(n).

If you have something that's Ω(f(n)) that means there's are k, g(n) such that f(n)k g(n).

And if you have a something with O(f(n)) and Ω(f(n)), then it's Θ(f(n).

The Wikipedia article is decent, if a little dense.

latex large division sign in a math formula

A possible soluttion that requires tweaking, but is very flexible is to use one of \big, \Big, \bigg,\Bigg in front of your division sign - these will make it progressively larger. For your formula, I think

  $\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$

looks nicer than \middle\ which is automatically sized and IMHO is a bit too large.

Select all 'tr' except the first one

You could create a class and use the class when you define all of your future 's that you want (or don't want) to be selected by the CSS.

This would be done by writing

<tr class="unselected">

and then in your css having the lines (and using the text-align command as an example) :

unselected {
  text-align:center;
}



selected {
  text-align:right;
}

How to make div background color transparent in CSS

The problem with opacity is that it will also affect the content, when often you do not want this to happen.

If you just want your element to be transparent, it's really as easy as :

background-color: transparent;

But if you want it to be in colors, you can use:

background-color: rgba(255, 0, 0, 0.4);

Or define a background image (1px by 1px) saved with the right alpha.
(To do so, use Gimp, Paint.Net or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)

As said by René, the best thing to do would be to mix both, with the rgba first and the 1px by 1px image as a fallback if the browser doesn't support alpha :

background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);

See also : http://www.w3schools.com/cssref/css_colors_legal.asp.

Demo : My JSFiddle

What's the fastest way to read a text file line-by-line?

To find the fastest way to read a file line by line you will have to do some benchmarking. I have done some small tests on my computer but you cannot expect that my results apply to your environment.

Using StreamReader.ReadLine

This is basically your method. For some reason you set the buffer size to the smallest possible value (128). Increasing this will in general increase performance. The default size is 1,024 and other good choices are 512 (the sector size in Windows) or 4,096 (the cluster size in NTFS). You will have to run a benchmark to determine an optimal buffer size. A bigger buffer is - if not faster - at least not slower than a smaller buffer.

const Int32 BufferSize = 128;
using (var fileStream = File.OpenRead(fileName))
  using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) {
    String line;
    while ((line = streamReader.ReadLine()) != null)
      // Process line
  }

The FileStream constructor allows you to specify FileOptions. For example, if you are reading a large file sequentially from beginning to end, you may benefit from FileOptions.SequentialScan. Again, benchmarking is the best thing you can do.

Using File.ReadLines

This is very much like your own solution except that it is implemented using a StreamReader with a fixed buffer size of 1,024. On my computer this results in slightly better performance compared to your code with the buffer size of 128. However, you can get the same performance increase by using a larger buffer size. This method is implemented using an iterator block and does not consume memory for all lines.

var lines = File.ReadLines(fileName);
foreach (var line in lines)
  // Process line

Using File.ReadAllLines

This is very much like the previous method except that this method grows a list of strings used to create the returned array of lines so the memory requirements are higher. However, it returns String[] and not an IEnumerable<String> allowing you to randomly access the lines.

var lines = File.ReadAllLines(fileName);
for (var i = 0; i < lines.Length; i += 1) {
  var line = lines[i];
  // Process line
}

Using String.Split

This method is considerably slower, at least on big files (tested on a 511 KB file), probably due to how String.Split is implemented. It also allocates an array for all the lines increasing the memory required compared to your solution.

using (var streamReader = File.OpenText(fileName)) {
  var lines = streamReader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  foreach (var line in lines)
    // Process line
}

My suggestion is to use File.ReadLines because it is clean and efficient. If you require special sharing options (for example you use FileShare.ReadWrite), you can use your own code but you should increase the buffer size.

How to center div vertically inside of absolutely positioned parent div

Here is simple way using Top object.

eg: If absolute element size is 60px.

.absolute-element { 
    position:absolute; 
    height:60px; 
    top: calc(50% - 60px);
}

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

Append same text to every cell in a column in Excel

Highlight the column and then Ctrl + F.

Find and replace

Find ".com"

Replace ".com, "

And then one for .in

Find and replace

Find ".in"

Replace ".in, "

Uri not Absolute exception getting while calling Restful Webservice

The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.

Execute SQL script from command line

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

Detect click event inside iframe

I know this is old but the ID's don't match in your code one is choose_pic and one is choose_pics:

<input type=button id=choose_pics value='Choose'>

$("#filecontainer").contents().find("#choose_pic").click(function(){
    //do something      
}); 

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

try avoiding use of view in xml design.I too had the same probem but when I removed the view. its worked perfectly.

like example:

             <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"                   
                android:hint="Username"
                android:inputType="number"                   
                android:textColor="#fff" />

            <view
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#f9d7db" />

also check and try changing by trial and error android:inputType="number" to android:inputType="text" or better not using it if not required .Sometimes keyboard stuck and gets error in some of the devices.

recyclerview No adapter attached; skipping layout

In my case it happened cause i embedded a RecyclerView in a LinearLayout.

I previously had a layout file only containing one root RecyclerView as follows

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:listitem="@layout/fragment_products"

    android:name="Products.ProductsFragment"
    app:layoutManager="LinearLayoutManager"
    tools:context=".Products.ProductsFragment"

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"/>

I believe the problem is within the 3 lines separated. Anyway, I think its a simple problem, ill be working on it tomorrow; thought i should write what i found before forgetting about this thread.

How to delete duplicates on a MySQL table?

If you want to keep the row with the lowest id value:

 DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.email = n2.email

If you want to keep the row with the highest id value:

 DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.email = n2.email

Can a PDF file's print dialog be opened with Javascript?

Another solution:

<input type="button" value="Print" onclick="document.getElementById('PDFtoPrint').focus(); document.getElementById('PDFtoPrint').contentWindow.print();">

Suppress output of a function

Making Hadley's comment to an answer (hope to make it better visible). Use of apply family without printing is possible with use of the plyr package

x <- 1:2
lapply(x, function(x) x + 1)
#> [[1]]
#> [1] 2
#> 
#> [[2]]
#> [1] 3

plyr::l_ply(x, function(x) x + 1)

Created on 2020-05-19 by the reprex package (v0.3.0)

PyCharm import external library

updated on May 26-2018

If the external library is in a folder that is under the project then

File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!

If not, add content root, and do similar things.

How do I remove an object from an array with JavaScript?

You can use either the splice() method or the delete operator.

The main difference is that when you delete an array element using the delete operator, the length of the array is not affected, even if you delete the last element of the array. On the other hand, the splice() method shifts all the elements such that no holes remain in the place of the deleted element.

Example using the delete operator:

var trees = ["redwood", "bay", "cedar", "oak", "maple"];  
delete trees[3];  
if (3 in trees) {  
   // this does not get executed  
}
console.log(trees.length);  //  5
console.log(trees);         //  ["redwood", "bay", "cedar", undefined, "maple"]

Example using the splice() method:

var trees = ["redwood", "bay", "cedar", "oak", "maple"];  
trees.splice(3, 1);
console.log(trees.length);  //  4
console.log(trees);         //  ["redwood", "bay", "cedar", "maple"]

How can INSERT INTO a table 300 times within a loop in SQL?

In ssms we can use GO to execute same statement

Edit This mean if you put

 some query

 GO n

Some query will be executed n times

Use cases for the 'setdefault' dict method

I use setdefault frequently when, get this, setting a default (!!!) in a dictionary; somewhat commonly the os.environ dictionary:

# Set the venv dir if it isn't already overridden:
os.environ.setdefault('VENV_DIR', '/my/default/path')

Less succinctly, this looks like this:

# Set the venv dir if it isn't already overridden:
if 'VENV_DIR' not in os.environ:
    os.environ['VENV_DIR'] = '/my/default/path')

It's worth noting that you can also use the resulting variable:

venv_dir = os.environ.setdefault('VENV_DIR', '/my/default/path')

But that's less necessary than it was before defaultdicts existed.

How can I use the HTML5 canvas element in IE?

I just used flashcanvas, and I got that working. If you encounter problems, just make sure to read the caveats and whatnot. Particularly, if you create canvas elements dynamically, you need to initialize them explicitly:

if (typeof FlashCanvas != "undefined") {
    FlashCanvas.initElement(canvas);
}

Eclipse Java error: This selection cannot be launched and there are no recent launches

Check if the filename is same as the classname used by your program.

eg.:

class Dfs{ psvm(String[] args){}}

filename should be Dfs.java

Find closest previous element jQuery

var link = $("#me").closest(":has(h3 span b)").find('span b').text();

What is the memory consumption of an object in Java?

No, registering an object takes a bit of memory too. 100 objects with 1 attribute will take up more memory.

How do I base64 encode (decode) in C?

libb64 has both C and C++ APIs. It is lightweight and perhaps the fastest publicly available implementation. It's also a dedicated stand-alone base64 encoding library, which can be nice if you don't need all the other stuff that comes from using a larger library such as OpenSSL or glib.

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

As it's already mentioned, runpy is a nice way to run other scripts or modules from current script.

By the way, it's quite common for a tracer or debugger to do this, and under such circumstances methods like importing the file directly or running the file in a subprocess usually do not work.

It also needs attention to use exec to run the code. You have to provide proper run_globals to avoid import error or some other issues. Refer to runpy._run_code for details.

Programmatically find the number of cores on a machine

Unrelated to C++, but on Linux I usually do:

grep processor /proc/cpuinfo | wc -l

Handy for scripting languages like bash/perl/python/ruby.

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Object of class stdClass could not be converted to string

try this

return $query->result_array();

JavaScript: How to get parent element by selector?

Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.matches(selector)) {
      retval = el;
      break
    } else if (stopSelector && el.matches(stopSelector)) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

Facebook Graph API : get larger pictures in one request

You can set the size of the picture in pixels, like this:

https://graph.facebook.com/v2.8/me?fields=id,name,picture.width(500).height(500)

In the similar manner, type parameter can be used

{user-id}/?fields=name,picture.type(large)

From the documentation

type enum{small, normal, album, large, square}

Wait for Angular 2 to load/resolve model before rendering view/template

The package @angular/router has the Resolve property for routes. So you can easily resolve data before rendering a route view.

See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html

Example from docs as of today, August 28, 2017:

class Backend {
  fetchTeam(id: string) {
    return 'someTeam';
  }
}

@Injectable()
class TeamResolver implements Resolve<Team> {
  constructor(private backend: Backend) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    return this.backend.fetchTeam(route.params.id);
  }
}

@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'team/:id',
        component: TeamCmp,
        resolve: {
          team: TeamResolver
        }
      }
    ])
  ],
  providers: [TeamResolver]
})
class AppModule {}

Now your route will not be activated until the data has been resolved and returned.

Accessing Resolved Data In Your Component

To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:

  1. route.snapshot.paramMap which returns a string, or the
  2. route.paramMap which returns an Observable you can .subscribe() to.

Example:

  // the no-observable method
  this.dataYouResolved= this.route.snapshot.paramMap.get('id');
  // console.debug(this.licenseNumber);

  // or the observable method
  this.route.paramMap
     .subscribe((params: ParamMap) => {
        // console.log(params);
        this.dataYouResolved= params.get('id');
        return params.get('dataYouResolved');
        // return null
     });
  console.debug(this.dataYouResolved);

I hope that helps.

IN-clause in HQL or Java Persistence Query Language

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

Count immediate child div elements using jQuery

In response to mrCoders answer using jsperf why not just use the dom node ?

var $foo = $('#foo');
var count = $foo[0].childElementCount

You can try the test here: http://jsperf.com/jquery-child-ele-size/7

This method gets 46,095 op/s while the other methods at best 2000 op/s

Trim string in JavaScript?

Simple version here What is a general function for JavaScript trim?

function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
}

Dynamic instantiation from string name of a class in dynamically imported module?

If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this

foo = __import__("foo")
bar = getattr(foo,"bar")
foo2 = getattr(bar,"foo2")

instance = foo2()

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:

df.orderBy(df.column_name.desc())

Doesn't require special imports.

Java regex to extract text between tags

To be quite honest, regular expressions are not the best idea for this type of parsing. The regular expression you posted will probably work great for simple cases, but if things get more complex you are going to have huge problems (same reason why you cant reliably parse HTML with regular expressions). I know you probably don't want to hear this, I know I didn't when I asked the same type of questions, but string parsing became WAY more reliable for me after I stopped trying to use regular expressions for everything.

jTopas is an AWESOME tokenizer that makes it quite easy to write parsers by hand (I STRONGLY suggest jtopas over the standard java scanner/etc.. libraries). If you want to see jtopas in action, here are some parsers I wrote using jTopas to parse this type of file

If you are parsing XML files, you should be using an xml parser library. Dont do it youself unless you are just doing it for fun, there are plently of proven options out there

How to multiply duration by integer?

My turn:

https://play.golang.org/p/RifHKsX7Puh

package main

import (
    "fmt"
    "time"
)

func main() {
    var n int = 77
    v := time.Duration( 1.15 * float64(n) ) * time.Second

    fmt.Printf("%v %T", v, v)
}

It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.

This way, conversion to/from time.Duration becomes a formality. Just remember:

  • int64
  • always nanosecs

Get webpage contents with Python?

Mechanize is a great package for "acting like a browser", if you want to handle cookie state, etc.

http://wwwsearch.sourceforge.net/mechanize/

How to Correctly Use Lists in R?

One reason lists work as they do (ordered) is to address the need for an ordered container that can contain any type at any node, which vectors do not do. Lists are re-used for a variety of purposes in R, including forming the base of a data.frame, which is a list of vectors of arbitrary type (but the same length).

Why do these two expressions not return the same result?

x = list(1, 2, 3, 4); x2 = list(1:4)

To add to @Shane's answer, if you wanted to get the same result, try:

x3 = as.list(1:4)

Which coerces the vector 1:4 into a list.

Read response headers from API response - Angular 5 + TypeScript

As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.

Here how we can do it in the WebAPI/MVC environment:

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

Another way is we can add code as below in the webApiconfig.cs file.

config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

**We can add custom headers in the web.config file as below. *

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Expose-Headers" value="TestHeaderToExpose" />
   </customHeaders>
</httpProtocol>

we can create an attribute and decore the method with the attribute.

Happy Coding !!

Stacking DIVs on top of each other?

I know that this post is a little old but I had the same problem and tried to fix it several hours. Finally I found the solution:

if we have 2 boxes positioned absolue

<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px;'></div>

we do expect that there will be one box on the screen. To do that we must set margin-bottom equal to -height, so doing like this:

<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>
<div style='left: 100px; top: 100px; position: absolute; width: 200px; height: 200px; margin-bottom: -200px;'></div>

works fine for me.

Focus Input Box On Load

A portable way of doing this is using a custom function (to handle browser differences) like this one.

Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:

window.onload = function() {
  document.getElementById("myinputbox").focus();
}

HTML text input field with currency symbol

I just used :before with the input and passed $ as the content

input{ 
   margin-left: 20px;
 }
input:before {
  content: "$";
  position: absolute;
}

You need to use a Theme.AppCompat theme (or descendant) with this activity

In my experiences the problem was the context where I showed my dialog. Inside a button click I instantiate an AlertDialog in this way:

builder = new AlertDialog.Builder(getApplicationContext());

But the context was not correct and caused the error. I've changed it using the application context in this way:

In declare section:

Context mContext;

in the onCreate method

mContext = this;

And finally in the code where I need the AlertDialog:

start_stop = (Button) findViewById(R.id.start_stop);
start_stop.setOnClickListener( new View.OnClickListener()
     {
                @Override
                public void onClick(View v)
                {
                    if (!is_running)
                    {
                        builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("MYTEXT")
                                .setCancelable(false)
                                .setPositiveButton("SI", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                    Task_Started = false;
                                    startTask();
                                    }
                                })
                                .setNegativeButton("NO",
                                        new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
            }
        }

This is the solution for me.

How to determine total number of open/active connections in ms sql server 2005

As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using' statement:

// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                filename = SaveToFileSystem(rdr, folderfilepath);
            }
        }
    }
}

How do I request and receive user input in a .bat and use it to run a certain program?

i just do :

set /p input= yes or no
if %input%==yes echo you clicked yes
if %input%==no echo you clicked no
pause

Convert from MySQL datetime to another format with PHP

If you're looking for a way to normalize a date into MySQL format, use the following

$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );

The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.

The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.

(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)

Load resources from relative path using local html in uiwebview

I crammed everything into one line (bad I know) and had no troubles with it:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         

How to check if a service is running on Android?

Again, another alternative that people might find cleaner if they use pending intents (for instance with the AlarmManager:

public static boolean isRunning(Class<? extends Service> serviceClass) {
    final Intent intent = new Intent(context, serviceClass);
    return (PendingIntent.getService(context, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null);
}

Where CODE is a constant that you define privately in your class to identify the pending intents associated to your service.

CSS - display: none; not working

Remove display: block; in the div #tfl style property

<div id="tfl" style="display: block; width: 187px; height: 260px;

Inline style take priority then css file

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

Jquery Change Height based on Browser Size/Resize

I have the feeling that the check should be different

new: h < 768 || w < 1024