Programs & Examples On #Controllercontext

System.Data.SqlClient.SqlException: Login failed for user

Numpty here used SQL authentication

enter image description here

instead of Windows (correct)

enter image description here

when adding the login to SQL Server, which also gives you this error if you are using Windows auth.

Non-static method requires a target

I think this confusing exception occurs when you use a variable in a lambda which is a null-reference at run-time. In your case, I would check if your variable calculationViewModel is a null-reference.

Something like:

public ActionResult MNPurchase()
{
    CalculationViewModel calculationViewModel = (CalculationViewModel)TempData["calculationViewModel"];

    if (calculationViewModel != null)
    {
        decimal OP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.SalesPrice)
            .FirstOrDefault()
            .OP;

        decimal MP = landTitleUnitOfWork.Sales.Find()
            .Where(x => x.Min >= calculationViewModel.MortgageAmount)
            .FirstOrDefault()
            .MP;

        calculationViewModel.LoanAmount = (OP + 100) - MP;
        calculationViewModel.LendersTitleInsurance = (calculationViewModel.LoanAmount + 850);

        return View(calculationViewModel);
    }
    else
    {
        // Do something else...
    }
}

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 asp.net tutorial

This happened to me because I created a new project which was trying to use System.Web.Providers DefaultMembershipProvider for membership. My DB and application was set up to use System.Web.Security.SqlMembershipProvider instead. I had to update the provider and connection string (since this provider seems to have some weird connection string requirements) to get it working.

An item with the same key has already been added

Most likely, you have model which contains the same property twice. Perhaps you are using new to hide the base property.

Solution is to override the property or use another name.

If you share your model, we would be able to elaborate more.

Mock HttpContext.Current in Test Init Method

If your application third party redirect internally, so it is better to mock HttpContext in below way :

HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };

Server cannot set status after HTTP headers have been sent IIS7.5

We were getting the same error - so this may be useful to some.

For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).

We fixed the issue and the user is no longer pressing the back button. Problem solved.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

I have tried almost all the answers from below list, but did not work for me. But read the exception well and then tried rename my Dbset name TransactionsModel to Transactions and it work for me.

old Code:

public class MyContext : DbContext
    {
        //....
        public DbSet<Models.TransactionsModel> TransactionsModel { get; set; }
    }

New Code:

public class MyContext : DbContext
    {
        //....
        public DbSet<Models.TransactionsModel> Transactions { get; set; }
    }

A generic error occurred in GDI+, JPEG Image to MemoryStream

You'll also get this exception if you try to save to an invalid path or if there's a permissions issue.

If you're not 100% sure that the file path is available and permissions are correct then try writing a to a text file. This takes just a few seconds to rule out what would be a very simple fix.

var img = System.Drawing.Image.FromStream(incomingStream);

// img.Save(path);
System.IO.File.WriteAllText(path, "Testing valid path & permissions.");

And don't forget to clean up your file.

How can I properly handle 404 in ASP.NET MVC?

Posting an answer since my comment was too long...

It's both a comment and questions to the unicorn post/answer:

https://stackoverflow.com/a/7499406/687549

I prefer this answer over the others for it's simplicity and the fact that apparently some folks at Microsoft were consulted. I got three questions however and if they can be answered then I will call this answer the holy grail of all 404/500 error answers on the interwebs for an ASP.NET MVC (x) app.

@Pure.Krome

  1. Can you update your answer with the SEO stuff from the comments pointed out by GWB (there was never any mentioning of this in your answer) - <customErrors mode="On" redirectMode="ResponseRewrite"> and <httpErrors errorMode="Custom" existingResponse="Replace">?

  2. Can you ask your ASP.NET team friends if it is okay to do it like that - would be nice to have some confirmation - maybe it's a big no-no to change redirectMode and existingResponse in this way to be able to play nicely with SEO?!

  3. Can you add some clarification surrounding all that stuff (customErrors redirectMode="ResponseRewrite", customErrors redirectMode="ResponseRedirect", httpErrors errorMode="Custom" existingResponse="Replace", REMOVE customErrors COMPLETELY as someone suggested) after talking to your friends at Microsoft?

As I was saying; it would be supernice if we could make your answer more complete as this seem to be a fairly popular question with 54 000+ views.

Update: Unicorn answer does a 302 Found and a 200 OK and cannot be changed to only return 404 using a route. It has to be a physical file which is not very MVC:ish. So moving on to another solution. Too bad because this seemed to be the ultimate MVC:ish answer this far.

How to render an ASP.NET MVC view as a string?

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

MVC2 .ascx style

protected string RenderViewToString<T>(string viewPath, T model) {
  ViewData.Model = model;
  using (var writer = new StringWriter()) {
    var view = new WebFormView(ControllerContext, viewPath);
    var vdd = new ViewDataDictionary<T>(model);
    var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                new TempDataDictionary(), writer);
    viewCxt.View.Render(viewCxt, writer);
    return writer.ToString();
  }
}

Razor .cshtml style

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

Edit: added Razor code.

Execution failed for task ':app:processDebugResources' even with latest build tools

I stucked for two days and finally found my solution. I changed the compileSdkVersion to 27 (same with buildToolsVersion)

compileSdkVersion 27
buildToolsVersion '27.0.3'

How to get MD5 sum of a string using python?

Have you tried using the MD5 implementation in hashlib? Note that hashing algorithms typically act on binary data rather than text data, so you may want to be careful about which character encoding is used to convert from text to binary data before hashing.

The result of a hash is also binary data - it looks like Flickr's example has then been converted into text using hex encoding. Use the hexdigest function in hashlib to get this.

How to get duplicate items from a list using LINQ?

Here's another option:

var list = new List<string> { "6", "1", "2", "4", "6", "5", "1" };

var set = new HashSet<string>();
var duplicates = list.Where(x => !set.Add(x));

Testing javascript with Mocha - how can I use console.log to debug a test?

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?

console.log(msg);

works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

How do I force git pull to overwrite everything on every pull?

If you haven't commit the local changes yet since the last pull/clone, you can use:

git checkout *
git pull

checkout will clear your local changes with the last local commit, and pull will sincronize it to the remote repository

Accessing Redux state in an action creator?

I agree with @Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:

import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';

class App extends React.Component {

  handleClick(){
    const data = this.props.someStateObject.data;
    this.props.someDispatchFunction(data);
  }

  render(){
    return (
      <div>       
      <div onClick={ this.handleClick.bind(this)}>Click Me!</div>      
      </div>
    );
  }
}


const mapStateToProps = (state) => {
  return { someStateObject: state.someStateObject };
};

const mapDispatchToProps = (dispatch) => {
  return {
    someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},

  };
}


export default connect(mapStateToProps, mapDispatchToProps)(App);

What is the best way to remove accents (normalize) in a Python unicode string?

gensim.utils.deaccent(text) from Gensim - topic modelling for humans:

'Sef chomutovskych komunistu dostal postou bily prasek'

Another solution is unidecode.

Note that the suggested solution with unicodedata typically removes accents only in some character (e.g. it turns 'l' into '', rather than into 'l').

MVC 3: How to render a view without its layout page when loaded via ajax?

Just put the following code on the top of the page

@{
    Layout = "";
}

Set Label Text with JQuery

I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});

Error during installing HAXM, VT-X not working

BIOS -> Overclockong -> CPU Features -> Intel Virtualization Tech -> Enabled

What are the Ruby File.open modes and options?

opt is new for ruby 1.9. The various options are documented in IO.new : www.ruby-doc.org/core/IO.html

Copying a rsa public key to clipboard

Does the file ~/.ssh/id_rsa.pub exist? If not, you need to generate one first:

ssh-keygen -t rsa -C "[email protected]"

qmake: could not find a Qt installation of ''

As Debian Qt's maintainer please allow me to suggest you to not use qtx-default. Please read qtchooser's man page, the solution is described there. If you are interested in packaging an app you can also take a look at this blog post I made explaining how to do it

# method 1
QT_SELECT=qt5 qmake

# method 2:
export QT_SELECT=qt5
qmake
... more qt commands here

# method 3:
make -qt5

To use Qt 4, just replace the qt5 with qt4

Update 20210202: starting from Debian 11 (bullseye) the packages qtx-default do not longer exist. Same goes for Ubuntu, but I don't know in which specific version. If you know of a package that still has the dependency (mostly non-Debian official packages) please file a bug. Same goes for Wiki pages, etc.

How to asynchronously call a method in Java

You can use @Async annotation from jcabi-aspects and AspectJ:

public class Foo {
  @Async
  public void save() {
    // to be executed in the background
  }
}

When you call save(), a new thread starts and executes its body. Your main thread continues without waiting for the result of save().

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Creating a simple configuration file and parser in C++

Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.

Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.

//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150

std::string ipName;
int nR, nC;

std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;

while (std::getline(fin, line)) {
 sin.str(line.substr(line.find("=")+1));
 if (line.find("Input name") != std::string::npos) {
  std::cout<<"Input name "<<sin.str()<<std::endl;
  sin >> ipName;
 }
 else if (line.find("Num. of rows") != std::string::npos) {
  sin >> nR;
 }
 else if (line.find("Num. of cols") != std::string::npos) {
  sin >> nC;
 }
 sin.clear();
}

Git Bash is extremely slow on Windows 7 x64

Only turning off AMD Radeon Graphics (or Intel Graphics) in Device Manager helped me.

enter image description here

I found the answer here: https://superuser.com/questions/1160349/git-is-extremely-slow-on-windows#=

System.Security.SecurityException when writing to Event Log

Though the installer answer is a good answer, it is not always practical when dealing with software you did not write. A simple answer is to create the log and the event source using the PowerShell command New-EventLog (http://technet.microsoft.com/en-us/library/hh849768.aspx)

Run PowerShell as an Administrator and run the following command changing out the log name and source that you need.

New-EventLog -LogName Application -Source TFSAggregator

I used it to solve the Event Log Exception when Aggregator runs issue from codeplex.

How to make a round button?

Round button in Android

You can make a ImageButton with circular background image.

Java Process with Input/Output Stream

You have writer.close(); in your code. So bash receives EOF on its stdin and exits. Then you get Broken pipe when trying to read from the stdoutof the defunct bash.

WindowsError: [Error 126] The specified module could not be found

NestedCaveats solution worked for me.

Imported my .dll files before importing torch and gpytorch, and all went smoothly.

So I just want to add that its not just importing pytorch but I can confirm that torch and gpytorch have this issue as well. I'd assume it covers any other torch-related libraries.

SQL Server : Transpose rows to columns

I had a slightly different requirement, whereby I had to selectively transpose columns into rows.

The table had columns:

create table tbl (ID, PreviousX, PreviousY, CurrentX, CurrentY)

I needed columns for Previous and Current, and rows for X and Y. A Cartesian product generated on a static table worked nicely, eg:

select 
    ID,
    max(case when metric='X' then PreviousX
        case when metric='Y' then PreviousY end) as Previous,
    max(case when metric='X' then CurrentX
        case when metric='Y' then CurrentY end) as Current
from tbl inner join
    /* Cartesian product - transpose by repeating row and 
    picking appropriate metric column for period */
    ( VALUES (1, 'X'), (2, 'Y')) AS x (sort, metric) ON 1=1
group by ID
order by ID, sort

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Mockito: Trying to spy on method is calling the original method

Bit late to the party but above solutions did not work for me , so sharing my 0.02$

Mokcito version: 1.10.19

MyClass.java

private int handleAction(List<String> argList, String action)

Test.java

MyClass spy = PowerMockito.spy(new MyClass());

Following did NOT work for me (actual method was being called):

1.

doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());

2.

doReturn(0).when(spy , "handleAction", any(), anyString());

3.

doReturn(0).when(spy , "handleAction", null, null);

Following WORKED:

doReturn(0).when(spy , "handleAction", any(List.class), anyString());

How to remove the querystring and get only the url?

Try this

$url_with_querystring = 'www.mydomian.com/myurl.html?unwantedthngs';
$url_data = parse_url($url_with_querystring);
$url_without_querystring = str_replace('?'.$url_data['query'], '', $url_with_querystring);

How to create local notifications?

In appdelegate.m file write the follwing code in applicationDidEnterBackground to get the local notification

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

How to deal with missing src/test/java source folder in Android/Maven project?

In the case of Maven project

Try right click on the project then select Maven -> Update Project... then Ok

Get content uri from file path in android

// This code works for images on 2.2, not sure if any other media types

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };

What is the __del__ method, How to call it?

The __del__ method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.

If you want to delete your object and thus call the __del__ method use

del obj1

which will delete the object (provided there weren't any other references to it).

I suggest you write a small class like this

class T:
    def __del__(self):
        print "deleted"

And investigate in the python interpreter, eg

>>> a = T()
>>> del a
deleted
>>> a = T()
>>> b = a
>>> del b
>>> del a
deleted
>>> def fn():
...     a = T()
...     print "exiting fn"
...
>>> fn()
exiting fn
deleted
>>>   

Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__ is called. It isn't considered good practice to use __del__ though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__ will be called either - the interpreter can exit in various ways without deleteting all objects.

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

Why should I use IHttpActionResult instead of HttpResponseMessage?

You might decide not to use IHttpActionResult because your existing code builds a HttpResponseMessage that doesn't fit one of the canned responses. You can however adapt HttpResponseMessage to IHttpActionResult using the canned response of ResponseMessage. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:

public IHttpActionResult SomeAction()
{
   IHttpActionResult response;
   //we want a 303 with the ability to set location
   HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
   responseMsg.Headers.Location = new Uri("http://customLocation.blah");
   response = ResponseMessage(responseMsg);
   return response;
}

Note, ResponseMessage is a method of the base class ApiController that your controller should inherit from.

How to prevent scrollbar from repositioning web page?

@kashesandr's solution worked for me but to hide horizontal scrollbar I added one more style for body. here is complete solution:

CSS

<style>
/* prevent layout shifting and hide horizontal scroll */
html {
  width: 100vw;
}
body {
  overflow-x: hidden;
}
</style>

JS

$(function(){
    /**
     * For multiple modals.
     * Enables scrolling of 1st modal when 2nd modal is closed.
     */
    $('.modal').on('hidden.bs.modal', function (event) {
      if ($('.modal:visible').length) {
        $('body').addClass('modal-open');
      }
    });
});

JS Only Solution (when 2nd modal opened from 1st modal):

/**
 * For multiple modals.
 * Enables scrolling of 1st modal when 2nd modal is closed.
 */
$('.modal').on('hidden.bs.modal', function (event) {
  if ($('.modal:visible').length) {
    $('body').addClass('modal-open');
    $('body').css('padding-right', 17);
  }
});

What is the difference between utf8mb4 and utf8 charsets in MySQL?

Taken from the MySQL 8.0 Reference Manual:

  • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

  • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

What do I use on linux to make a python program executable

You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.

http://pythonhosted.org/PyInstaller/#using-pyinstaller

Python 3 has the native option of create a build dist also:

https://docs.python.org/3/distutils/builtdist.html

PHP date() with timezone?

The answer above caused me to jump through some hoops/gotchas, so just posting the cleaner code that worked for me:

$dt = new DateTime();
$dt->setTimezone(new DateTimeZone('America/New_York'));
$dt->setTimestamp(123456789);

echo $dt->format('F j, Y @ G:i');

symfony 2 No route found for "GET /"

Using symfony 2.3 with php 5.5 and using the built in server with

app/console server:run

which should output something like:

Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.

then go to http://127.0.0.1:8000/app_dev.php/app/example

this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php

Convert boolean to int in Java

If you use Apache Commons Lang (which I think a lot of projects use it), you can just use it like this:

int myInt = BooleanUtils.toInteger(boolean_expression); 

toInteger method returns 1 if boolean_expression is true, 0 otherwise

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

SQL Query - Concatenating Results into One String

Here is another real life example that works fine at least with 2008 release (and later).

This is the original query which uses simple max() to get at least one of the values:

SELECT option_name, Field_M3_name, max(Option_value) AS "Option value", max(Sorting) AS "Sorted"
FROM Value_list group by Option_name, Field_M3_name
ORDER BY option_name, Field_M3_name

Improved version, where the main improvement is that we show all values comma separated:

SELECT from1.keys, from1.option_name, from1.Field_M3_name,

 Stuff((SELECT DISTINCT ', ' + [Option_value] FROM Value_list from2
  WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'') AS "Option values",

 Stuff((SELECT DISTINCT ', ' + CAST([Sorting] AS VARCHAR) FROM Value_list from2
  WHERE COALESCE(from2.Option_name,'') + '|' + COALESCE(from2.Field_M3_name,'') = from1.keys FOR XML PATH(''),TYPE)
  .value('text()[1]','nvarchar(max)'),1,2,N'') AS "Sorting"

FROM ((SELECT DISTINCT COALESCE(Option_name,'') + '|' + COALESCE(Field_M3_name,'') AS keys, Option_name, Field_M3_name FROM Value_list)
-- WHERE
) from1
ORDER BY keys

Note that we have solved all possible NULL case issues that I can think of and also we fixed an error that we got for numeric values (field Sorting).

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

Only changing the settings with the following command did not work in my environment:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

I had to also ran the Force Merge API command:

curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"

ref: Force Merge API

How do you change the width and height of Twitter Bootstrap's tooltips?

I had the same problem, however all popular answers - to change .tooltip-inner{width} for my task failed to do the job right. As for other (i.e. shorter) tooltips fixed width was too big. I was lazy to write separate html templates/classes for zilions of tooltips, so I just replaced all spaces between words with &nbsp; in each text line.

Ant is using wrong java version

Just had this issue, it happened because I'd first added the build file to the ant-view when the default JRE was 1.6.

There was no project-specific JRE and I changed the default to 1.5, even eclipse was running in 1.5, and JAVA_HOME was 1.5 too. Running the ant target from the command line used JRE 1.5, but within eclipse it still used 1.6.

I had to right-click the ant target, select Run As... and change the JRE under the JRE tab. This setting is remembered for subsequent runs.

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

Handle Guzzle exception and get HTTP body

None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):

try {
    // call here
} catch (\GuzzleHttp\Exception\RequestException $e) {
    if ($e->hasResponse()) {
        $response = $e->getResponse();
        // message is in $response->getReasonPhrase()
    } else {
        $response = $e->getHandlerContext();
        if (isset($response['error'])) {
            // message is in $response['error']
        } else {
            // Unknown error occured!
        }
    }
}

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

OS X Terminal UTF-8 issues

For me, this helped: I checked locale on my local shell in terminal

$ locale
LANG="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"

Then connected to any remote host I am using via ssh and edited file /etc/profile as root - at the end I added line:

export LANG=cs_CZ.UTF-8

After next connection it works fine in bash, ls and nano.

Encrypt and Decrypt in Java

Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.

Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.

DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.

Steps :

  1. Add the Security Provider : We are using the SunJCE Provider that is available with the JDK.
  2. Generate Secret Key : Use KeyGenerator and an algorithm to generate a secret key. We are using DESede.
  3. Encode Text : For consistency across platform encode the plain text as byte using UTF-8 encoding.
  4. Encrypt Text : Instantiate Cipher with ENCRYPT_MODE, use the secret key and encrypt the bytes.
  5. Decrypt Text : Instantiate Cipher with DECRYPT_MODE, use the same secret key and decrypt the bytes.

All the above given steps and concept are same, we just replace algorithms.

import java.util.Base64;    
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;  
public class EncryptionDecryptionAES {  
    static Cipher cipher;  

    public static void main(String[] args) throws Exception {
        /* 
         create key 
         If we need to generate a new key use a KeyGenerator
         If we have existing plaintext key use a SecretKeyFactory
        */ 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

        /*
          Cipher Info
          Algorithm : for the encryption of electronic data
          mode of operation : to avoid repeated blocks encrypt to the same values.
          padding: ensuring messages are the proper length necessary for certain ciphers 
          mode/padding are not used with stream cyphers.  
         */
        cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  

        String plainText = "AES Symmetric Encryption Decryption";
        System.out.println("Plain Text Before Encryption: " + plainText);

        String encryptedText = encrypt(plainText, secretKey);
        System.out.println("Encrypted Text After Encryption: " + encryptedText);

        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text After Decryption: " + decryptedText);
    }

    public static String encrypt(String plainText, SecretKey secretKey)
            throws Exception {
        byte[] plainTextByte = plainText.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedText = encoder.encodeToString(encryptedByte);
        return encryptedText;
    }

    public static String decrypt(String encryptedText, SecretKey secretKey)
            throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }
}

Output:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption

Source

Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text. enter image description here

How to remove space from string?

You can also use echo to remove blank spaces, either at the beginning or at the end of the string, but also repeating spaces inside the string.

$ myVar="    kokor    iiij     ook      "
$ echo "$myVar"
    kokor    iiij     ook      
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook

JavaScriptSerializer.Deserialize - how to change field names

I have used the using Newtonsoft.Json as below. Create an object:

 public class WorklistSortColumn
  {
    [JsonProperty(PropertyName = "field")]
    public string Field { get; set; }

    [JsonProperty(PropertyName = "dir")]
    public string Direction { get; set; }

    [JsonIgnore]
    public string SortOrder { get; set; }
  }

Now Call the below method to serialize to Json object as shown below.

string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

Set LIMIT with doctrine 2?

Your setMaxResults($limit) needs to be set on the object.

e.g.

$query_ids = $this->getEntityManager()
  ->createQuery(
    "SELECT e_.id
    FROM MuzichCoreBundle:Element e_
    WHERE [...]
    GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

Addition to Alex' answer:

JavaScript

$(function() {
    $('input[type="submit"]').prop('disabled', true);
    $('#check').on('input', function(e) {
        if(this.value.length === 6) {
            $('input[type="submit"]').prop('disabled', false);
        } else {
            $('input[type="submit"]').prop('disabled', true);
        }
    });
});

HTML

<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />

JsFiddle

But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.

How to check if the URL contains a given string?

The regex way:

var matches = !!location.href.match(/franky/); //a boolean value now

Or in a simple statement you could use:

if (location.href.match(/franky/)) {

I use this to test whether the website is running locally or on a server:

location.href.match(/(192.168|localhost).*:1337/)

This checks whether the href contains either 192.168 or localhost AND is followed by :1337.

As you can see, using regex has its advantages over the other solutions when the condition gets a bit trickier.

How do I sort strings alphabetically while accounting for value when a string is numeric?

Try this out..  



  string[] things = new string[] { "paul", "bob", "lauren", "007", "90", "-10" };

        List<int> num = new List<int>();
        List<string> str = new List<string>();
        for (int i = 0; i < things.Count(); i++)
        {

            int result;
            if (int.TryParse(things[i], out result))
            {
                num.Add(result);
            }
            else
            {
                str.Add(things[i]);
            }


        }

Now Sort the lists and merge them back...

        var strsort = from s in str
                      orderby s.Length
                      select s;

        var numsort = from n in num
                     orderby n
                     select n;

        for (int i = 0; i < things.Count(); i++)
        {

         if(i < numsort.Count())
             things[i] = numsort.ElementAt(i).ToString();
             else
             things[i] = strsort.ElementAt(i - numsort.Count());               
               }

I jsut tried to make a contribution in this interesting question...

Increase number of axis ticks

You can override ggplots default scales by modifying scale_x_continuous and/or scale_y_continuous. For example:

library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))

ggplot(dat, aes(x,y)) +
  geom_point()

Gives you this:

enter image description here

And overriding the scales can give you something like this:

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks = round(seq(min(dat$x), max(dat$x), by = 0.5),1)) +
  scale_y_continuous(breaks = round(seq(min(dat$y), max(dat$y), by = 0.5),1))

enter image description here

If you want to simply "zoom" in on a specific part of a plot, look at xlim() and ylim() respectively. Good insight can also be found here to understand the other arguments as well.

Should I use Java's String.format() if performance is important?

The answer to this depends very much on how your specific Java compiler optimizes the bytecode it generates. Strings are immutable and, theoretically, each "+" operation can create a new one. But, your compiler almost certainly optimizes away interim steps in building long strings. It's entirely possible that both lines of code above generate the exact same bytecode.

The only real way to know is to test the code iteratively in your current environment. Write a QD app that concatenates strings both ways iteratively and see how they time out against each other.

Python socket receive - incoming packets always have a different size

The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module.

So, to clarify, since this may be confusing to others looking to this for help:

  1. The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param).
  2. The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available.

See the documentation for details.

Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.

As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.

I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.

Why aren't python nested functions called closures?

A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.

def make_printer(msg):
    def printer():
        print msg
    return printer

printer = make_printer('Foo!')
printer()

When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant and the value of msg as a local. It then creates and returns the function. Because the function printer references the msg variable, it is kept alive after the make_printer function has returned.

So, if your nested functions don't

  1. access variables that are local to enclosing scopes,
  2. do so when they are executed outside of that scope,

then they are not closures.

Here's an example of a nested function which is not a closure.

def make_printer(msg):
    def printer(msg=msg):
        print msg
    return printer

printer = make_printer("Foo!")
printer()  #Output: Foo!

Here, we are binding the value to the default value of a parameter. This occurs when the function printer is created and so no reference to the value of msg external to printer needs to be maintained after make_printer returns. msg is just a normal local variable of the function printer in this context.

PHP: HTTP or HTTPS?

If your request is sent by HTTPS you will have an extra server variable named 'HTTPS'

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { //HTTPS } 

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

JavaScript hide/show element

If you are using it in a table use this :-

  <script type="text/javascript">
   function showStuff(id, text, btn) {
    document.getElementById(id).style.display = 'table-row';
    // hide the lorem ipsum text
    document.getElementById(text).style.display = 'none';
    // hide the link
    btn.style.display = 'none';
}
</script>


<td class="post">

<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>
<span id="answer1" style="display: none;">
<textarea rows="10" cols="115"></textarea>
</span>

<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>
</td>

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Because you may include two same libs in your project. check your build.gradle file.

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile files('libs/android-support-v4.jar') 
 }

if your file includes compile 'com.android.support:appcompat-v7:+' and compile files('libs/android-support-v4.jar'), it will have this problems. delete this sentence: compile files('libs/android-support-v4.jar')

That's how I fix this problem.

What is the difference between Promises and Observables?

A Promise emits a single event when an async activity finishes or fails.

An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.

Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.

Promise: promise emits a single value

For example:

const numberPromise = new Promise((resolve) => {
    resolve(5);
    resolve(10);
});

numberPromise.then(value => console.log(value));
// still prints only 5

Observable: Emits multiple values over a period of time

For example:

  const numberObservable = new Observable((observer) => {
        observer.next(5);
        observer.next(10);
    });

numberObservable.subscribe(value => console.log(value));
// prints 5 and 10

we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

Promise:

  • A promise is Not Lazy
  • A Promise cannot be cancelled

Observable:

  • Observable is Lazy. The "Observable" is slow. It isn't called until we are subscribed to it.
  • An Observable can be cancelled by using the unsubscribe() method
  • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

Angular Promises vs Observables

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

My view is to always use ++ and -- by themselves on a single line, as in:

i++;
array[i] = foo;

instead of

array[++i] = foo;

Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

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

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

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

This issue occured for me in Visual studio 2015.

Reason:

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

Possible Fix

Step1:

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

Navigate to Nuget Package Manager Console as

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

Then enter the following command in console as below

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

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

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

Step2:-

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

Step3:

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

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

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

Difference between sh and bash

bash and sh are two different shells. Basically bash is sh, with more features and better syntax. Most commands work the same, but they are different.Bash (bash) is one of many available (yet the most commonly used) Unix shells. Bash stands for "Bourne Again SHell",and is a replacement/improvement of the original Bourne shell (sh).

Shell scripting is scripting in any shell, whereas Bash scripting is scripting specifically for Bash. In practice, however, "shell script" and "bash script" are often used interchangeably, unless the shell in question is not Bash.

Having said that, you should realize /bin/sh on most systems will be a symbolic link and will not invoke sh. In Ubuntu /bin/sh used to link to bash, typical behavior on Linux distributions, but now has changed to linking to another shell called dash. I would use bash, as that is pretty much the standard (or at least most common, from my experience). In fact, problems arise when a bash script will use #!/bin/sh because the script-maker assumes the link is to bash when it doesn't have to be.

preventDefault() on an <a> tag

It's suggested that you do not use return false, as 3 things occur as a result:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

So in this type of situation, you should really only use event.preventDefault();

Archive of article - jQuery Events: Stop (Mis)Using Return False

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("http://stackoverflow.com");

How to properly use the "choices" field option in Django

For Django3.0+, use models.TextChoices (see docs-v3.0 for enumeration types)

from django.db import models

class MyModel(models.Model):
    class Month(models.TextChoices):
        JAN = '1', "JANUARY"
        FEB = '2', "FEBRUARY"
        MAR = '3', "MAR"
        # (...)

    month = models.CharField(
        max_length=2,
        choices=Month.choices,
        default=Month.JAN
    )

Usage::

>>> obj = MyModel.objects.create(month='1')
>>> assert obj.month == obj.Month.JAN
>>> assert MyModel.Month(obj.month).label == 'JANUARY'
>>> assert MyModel.objects.filter(month=MyModel.Month.JAN).count() >= 1

>>> obj2 = MyModel(month=MyModel.Month.FEB)
>>> assert obj2.get_month_display() == obj2.Month(obj2.month).label

How can I add a PHP page to WordPress?

Any answer did not cover if you need to add a PHP page outside of the WordPress Theme. This is the way.

You need to include wp-load.php.

<?php require_once('wp-load.php'); ?>

Then you can use any WordPress function on that page.

Guzzle 6: no more json() method for responses

If you guys still interested, here is my workaround based on Guzzle middleware feature:

  1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:

    <?php
    
    namespace GuzzleHttp\Psr7;
    
    
    class JsonAwareResponse extends Response
    {
        /**
         * Cache for performance
         * @var array
         */
        private $json;
    
        public function getBody()
        {
            if ($this->json) {
                return $this->json;
            }
            // get parent Body stream
            $body = parent::getBody();
    
            // if JSON HTTP header detected - then decode
            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                return $this->json = \json_decode($body, true);
            }
            return $body;
        }
    }
    
  2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:

    <?php
    
    $client = new \GuzzleHttp\Client();
    
    /** @var HandlerStack $handler */
    $handler = $client->getConfig('handler');
    $handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
        return new \GuzzleHttp\Psr7\JsonAwareResponse(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
    }), 'json_decode_middleware');
    

After this to retrieve JSON as PHP native array use Guzzle as always:

$jsonArray = $client->get('http://httpbin.org/headers')->getBody();

Tested with guzzlehttp/guzzle 6.3.3

Do you use NULL or 0 (zero) for pointers in C++?

I once worked on a machine where 0 was a valid address and NULL was defined as a special octal value. On that machine (0 != NULL), so code such as

char *p;

...

if (p) { ... }

would not work as you expect. You HAD to write

if (p != NULL) { ... }

Although I believe most compilers define NULL as 0 these days I still remember the lesson from those years ago: NULL is not necessarily 0.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to remove foreign key constraint in sql server?

Try following

ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>

Refer : http://www.w3schools.com/sql/sql_foreignkey.asp

How do I float a div to the center?

Simple solution:

<style>
.center {
    margin: auto;

}
</style>

<div class="center">
    <p> somthing goes here </p>
</div>

Try Online

How do I make WRAP_CONTENT work on a RecyclerView

Update your view with null value instead of parent viewgroup in Adapter viewholder onCreateViewHolder method.

@Override
public AdapterItemSku.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflator.inflate(R.layout.layout_item, null, false);
    return new MyViewHolder(view);
}

Check if a string is not NULL or EMPTY

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

How can I take a screenshot/image of a website using Python?

Here is my solution by grabbing help from various sources. It takes full web page screen capture and it crops it (optional) and generates thumbnail from the cropped image also. Following are the requirements:

Requirements:

  1. Install NodeJS
  2. Using Node's package manager install phantomjs: npm -g install phantomjs
  3. Install selenium (in your virtualenv, if you are using that)
  4. Install imageMagick
  5. Add phantomjs to system path (on windows)

import os
from subprocess import Popen, PIPE
from selenium import webdriver

abspath = lambda *p: os.path.abspath(os.path.join(*p))
ROOT = abspath(os.path.dirname(__file__))


def execute_command(command):
    result = Popen(command, shell=True, stdout=PIPE).stdout.read()
    if len(result) > 0 and not result.isspace():
        raise Exception(result)


def do_screen_capturing(url, screen_path, width, height):
    print "Capturing screen.."
    driver = webdriver.PhantomJS()
    # it save service log file in same directory
    # if you want to have log file stored else where
    # initialize the webdriver.PhantomJS() as
    # driver = webdriver.PhantomJS(service_log_path='/var/log/phantomjs/ghostdriver.log')
    driver.set_script_timeout(30)
    if width and height:
        driver.set_window_size(width, height)
    driver.get(url)
    driver.save_screenshot(screen_path)


def do_crop(params):
    print "Croping captured image.."
    command = [
        'convert',
        params['screen_path'],
        '-crop', '%sx%s+0+0' % (params['width'], params['height']),
        params['crop_path']
    ]
    execute_command(' '.join(command))


def do_thumbnail(params):
    print "Generating thumbnail from croped captured image.."
    command = [
        'convert',
        params['crop_path'],
        '-filter', 'Lanczos',
        '-thumbnail', '%sx%s' % (params['width'], params['height']),
        params['thumbnail_path']
    ]
    execute_command(' '.join(command))


def get_screen_shot(**kwargs):
    url = kwargs['url']
    width = int(kwargs.get('width', 1024)) # screen width to capture
    height = int(kwargs.get('height', 768)) # screen height to capture
    filename = kwargs.get('filename', 'screen.png') # file name e.g. screen.png
    path = kwargs.get('path', ROOT) # directory path to store screen

    crop = kwargs.get('crop', False) # crop the captured screen
    crop_width = int(kwargs.get('crop_width', width)) # the width of crop screen
    crop_height = int(kwargs.get('crop_height', height)) # the height of crop screen
    crop_replace = kwargs.get('crop_replace', False) # does crop image replace original screen capture?

    thumbnail = kwargs.get('thumbnail', False) # generate thumbnail from screen, requires crop=True
    thumbnail_width = int(kwargs.get('thumbnail_width', width)) # the width of thumbnail
    thumbnail_height = int(kwargs.get('thumbnail_height', height)) # the height of thumbnail
    thumbnail_replace = kwargs.get('thumbnail_replace', False) # does thumbnail image replace crop image?

    screen_path = abspath(path, filename)
    crop_path = thumbnail_path = screen_path

    if thumbnail and not crop:
        raise Exception, 'Thumnail generation requires crop image, set crop=True'

    do_screen_capturing(url, screen_path, width, height)

    if crop:
        if not crop_replace:
            crop_path = abspath(path, 'crop_'+filename)
        params = {
            'width': crop_width, 'height': crop_height,
            'crop_path': crop_path, 'screen_path': screen_path}
        do_crop(params)

        if thumbnail:
            if not thumbnail_replace:
                thumbnail_path = abspath(path, 'thumbnail_'+filename)
            params = {
                'width': thumbnail_width, 'height': thumbnail_height,
                'thumbnail_path': thumbnail_path, 'crop_path': crop_path}
            do_thumbnail(params)
    return screen_path, crop_path, thumbnail_path


if __name__ == '__main__':
    '''
        Requirements:
        Install NodeJS
        Using Node's package manager install phantomjs: npm -g install phantomjs
        install selenium (in your virtualenv, if you are using that)
        install imageMagick
        add phantomjs to system path (on windows)
    '''

    url = 'http://stackoverflow.com/questions/1197172/how-can-i-take-a-screenshot-image-of-a-website-using-python'
    screen_path, crop_path, thumbnail_path = get_screen_shot(
        url=url, filename='sof.png',
        crop=True, crop_replace=False,
        thumbnail=True, thumbnail_replace=False,
        thumbnail_width=200, thumbnail_height=150,
    )

These are the generated images:

How to Convert Int to Unsigned Byte and Back

If you want to use the primitive wrapper classes, this will work, but all java types are signed by default.

public static void main(String[] args) {
    Integer i=5;
    Byte b = Byte.valueOf(i+""); //converts i to String and calls Byte.valueOf()
    System.out.println(b);
    System.out.println(Integer.valueOf(b));
}

python date of the previous month

import pandas as pd

lastmonth = int(pd.to_datetime("today").strftime("%Y%m"))-1

print(lastmonth)

202101

Access all Environment properties as a Map or Properties object

Working with Spring Boot 2, I needed to do something similar. Most of the answers above work fine, just beware that at various phases in the app lifecycles the results will be different.

For example, after a ApplicationEnvironmentPreparedEvent any properties inside application.properties are not present. However, after a ApplicationPreparedEvent event they are.

Setting POST variable without using form

you can do it using ajax or by sending http headers+content like:

POST /xyz.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

@selector() in Swift?

Just in case somebody else have the same problem I had with NSTimer where none of the other answers fixed the issue, is really important to mention that, if you are using a class that do not inherits from NSObject either directly or deep in the hierarchy(e.g. manually created swift files), none of the other answers will work even when is specified as follows:

let timer = NSTimer(timeInterval: 1, target: self, selector: "test", 
                    userInfo: nil, repeats: false)
func test () {}

Without changing anything else other than just making the class inherit from NSObject I stopped getting the "Unrecognized selector" Error and got my logic working as expected.

How to split a number into individual digits in c#?

You can simply do:

"123456".Select(q => new string(q,1)).ToArray();

to have an enumerable of integers, as per comment request, you can:

"123456".Select(q => int.Parse(new string(q,1))).ToArray();

It is a little weak since it assumes the string actually contains numbers.

Loop through an array php

Ok, I know there is an accepted answer but… for more special cases you also could use this one:

array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array);

Or in a more un-complex way:

function printItem($n){
    echo $n['filename'];
    echo $n['filepath'];
}

array_map('printItem', $array);

This will allow you to manipulate the data in an easier way.

If Browser is Internet Explorer: run an alternative script instead

For IE10+ standard conditions don't work cause of engine change or some another reasons, cause, you know, it's MSIE. But for IE10+ you need to run something like this in your scripts:

if (navigator.userAgent.match(/Trident\/7\./)) {
  // do stuff for IE.
}

How do I resolve a HTTP 414 "Request URI too long" error?

I have a simple workaround.

Suppose your URI has a string stringdata that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.

Required attribute on multiple checkboxes with the same name?

Building on icova's answer, here's the code so you can use a custom HTML5 validation message:

$(function() {
    var requiredCheckboxes = $(':checkbox[required]');
    requiredCheckboxes.change(function() {
        if (requiredCheckboxes.is(':checked')) {requiredCheckboxes.removeAttr('required');}
        else {requiredCheckboxes.attr('required', 'required');}
    });
    $("input").each(function() {
        $(this).on('invalid', function(e) {
            e.target.setCustomValidity('');
            if (!e.target.validity.valid) {
                e.target.setCustomValidity('Please, select at least one of these options');
            }
        }).on('input, click', function(e) {e.target.setCustomValidity('');});
    });
});

Convert NSDate to String in iOS Swift

DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:

extension Date {  
  func asString(style: DateFormatter.Style) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = style
    return dateFormatter.string(from: self)
  }
}

This gives you the following styles:

short, medium, long, full

Example usage:

let myDate = Date()
myDate.asString(style: .full)   // Wednesday, January 10, 2018
myDate.asString(style: .long)   // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short)  // 1/10/18

How can I extract a predetermined range of lines from a text file on Unix?

perl -ne 'print if 16224..16482' file.txt > new_file.txt

Use Font Awesome Icon in Placeholder

I do this by adding fa-placeholder class to input text:

<input type="text" name="search" class="form-control" placeholder="&#xF002;" />

so, in css just add this:

.fa-placholder { font-family: "FontAwesome"; }

It works well for me.

Update:

To change font while user type in your text input, just add your font after font awesome

.fa-placholder { font-family: "FontAwesome", "Source Sans Pro"; }

AngularJS - ng-if check string empty value

You don't need to explicitly use qualifiers like item.photo == '' or item.photo != ''. Like in JavaScript, an empty string will be evaluated as false.

Your views will be much cleaner and readable as well.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>_x000D_
<div ng-app init="item = {photo: ''}">_x000D_
   <div ng-if="item.photo"> show if photo is not empty</div>_x000D_
   <div ng-if="!item.photo"> show if photo is empty</div>_x000D_
  _x000D_
   <input type=text ng-model="item.photo" placeholder="photo" />_x000D_
</div
_x000D_
_x000D_
_x000D_

Updated to remove bug in Angular

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Inner text shadow with CSS

There's no need for multiple shadows or anything fancy like that, you just have to offset your shadow in the negative y-axis.

For dark text on a light background:

text-shadow: 0px -1px 0px rgba(0, 0, 0, .75);

If you have a dark background then you can simply invert the color and y-position:

text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.75);

Play around with the rgba values, the opacity, and the blur to get the effect just right. It will depend a lot on what color font and background you have, and the weightier the font, the better.

How to get the filename without the extension from a path in Python?

In Python 3.4+ you can use the pathlib solution

from pathlib import Path

print(Path(your_path).resolve().stem)

Serialize object to query string in JavaScript/jQuery

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

Find location of a removable SD card

This solution handles the fact that System.getenv("SECONDARY_STORAGE") is of no use with Marshmallow.

Tested and working on:

  • Samsung Galaxy Tab 2 (Android 4.1.1 - Stock)
  • Samsung Galaxy Note 8.0 (Android 4.2.2 - Stock)
  • Samsung Galaxy S4 (Android 4.4 - Stock)
  • Samsung Galaxy S4 (Android 5.1.1 - Cyanogenmod)
  • Samsung Galaxy Tab A (Android 6.0.1 - Stock)

    /**
     * Returns all available external SD-Card roots in the system.
     *
     * @return paths to all available external SD-Card roots in the system.
     */
    public static String[] getStorageDirectories() {
        String [] storageDirectories;
        String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            List<String> results = new ArrayList<String>();
            File[] externalDirs = applicationContext.getExternalFilesDirs(null);
            for (File file : externalDirs) {
                String path = file.getPath().split("/Android")[0];
                if((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file))
                        || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)){
                    results.add(path);
                }
            }
            storageDirectories = results.toArray(new String[0]);
        }else{
            final Set<String> rv = new HashSet<String>();
    
            if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                Collections.addAll(rv, rawSecondaryStorages);
            }
            storageDirectories = rv.toArray(new String[rv.size()]);
        }
        return storageDirectories;
    }
    

Looping through rows in a DataView

I prefer to do it in a more direct fashion. It does not have the Rows but is still has the array of rows.

tblCrm.DefaultView.RowFilter = "customertype = 'new'";

qtytotal = 0;
for (int i = 0; i < tblCrm.DefaultView.Count; i++)
{
    result = double.TryParse(tblCrm.DefaultView[i]["qty"].ToString(), out num);
    if (result == false) num = 0;
    qtytotal = qtytotal + num;
}

labQty.Text = qtytotal.ToString();

Simulate low network connectivity for Android

I'm surprised nobody mentioned this. You can tether via Bluetooth, and separate them by ten+ meters(or less with obstacles). You've got a real bad connection. No microwave, no elevator, no software needed.

Adding attributes to an XML node

You can use the Class XmlAttribute.

Eg:

XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";

node.Attributes.Append(attr);

jQuery ajax success callback function definition

Try rewriting your success handler to:

success : handleData

The success property of the ajax method only requires a reference to a function.

In your handleData function you can take up to 3 parameters:

object data
string textStatus
jqXHR jqXHR

Split output of command by columns using Bash?

Using array variables

set $(ps | egrep "^11383 "); echo $4

or

A=( $(ps | egrep "^11383 ") ) ; echo ${A[3]}

Validate fields after user has left a field

based on @nicolas answer.. Pure CSS should the trick, it will only show the error message on blur

<input type="email" id="input-email" required
               placeholder="Email address" class="form-control" name="email"
               ng-model="userData.email">
        <p ng-show="form.email.$error.email" class="bg-danger">This is not a valid email.</p>

CSS

.ng-invalid:focus ~ .bg-danger {
     display:none;
}

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I had this error on AWS Lightsail, used the top answer above

from

listen [::]:80;

to

listen [::]:80 ipv6only=on default_server;

and then click on "reboot" button inside my AWS account, I have main server Apache and Nginx as proxy.

How to draw interactive Polyline on route google maps v2 android

Instead of creating too many short Polylines just create one like here:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

I'm also not sure you should use geodesic when your points are so close to each other.

Get DateTime.Now with milliseconds precision

Pyromancer's answer seems pretty good to me, but maybe you wanted:

DateTime.Now.Millisecond

But if you are comparing dates, TimeSpan is the way to go.

Image inside div has extra space below the image

One can also nullify parent's line height:

#wrapper {
  line-height: 0;
}

All fixes: http://jsfiddle.net/FaPFv/

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

How can I list ALL DNS records?

  1. A zone transfer is the only way to be sure you have all the subdomain records. If the DNS is correctly configured you should not normally be able to perform an external zone transfer.

  2. The scans.io project has a database of DNS records that can be downloaded and searched for subdomains. This requires downloading the 87GB of DNS data, alternatively you can try the online search of the data at https://hackertarget.com/find-dns-host-records/

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Can I stop 100% Width Text Boxes from extending beyond their containers?

This solved the problem for me!

Without the need for an external div. Just apply it to your given text box.

box-sizing: border-box; 

With this property "The width and height properties (and min/max properties) includes content, padding and border, but not the margin"

See description of property at w3schools.

Hope this helps someone!

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Following solution is clean and works perfectly.

  1. Download Elevate zip file from https://www.winability.com/download/Elevate.zip

  2. Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)

  3. Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.

  4. To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:

 elevate net start service ...

How to send FormData objects with Ajax-requests in jQuery?

JavaScript:

function submitForm() {
    var data1 = new FormData($('input[name^="file"]'));
    $.each($('input[name^="file"]')[0].files, function(i, file) {
        data1.append(i, file);
    });

    $.ajax({
        url: "<?php echo base_url() ?>employee/dashboard2/test2",
        type: "POST",
        data: data1,
        enctype: 'multipart/form-data',
        processData: false, // tell jQuery not to process the data
        contentType: false // tell jQuery not to set contentType
    }).done(function(data) {
        console.log("PHP Output:");
        console.log(data);
    });
    return false;
}

PHP:

public function upload_file() {
    foreach($_FILES as $key) {
        $name = time().$key['name'];
        $path = 'upload/'.$name;
        @move_uploaded_file($key['tmp_name'], $path);
    }
}

Convert byte to string in Java

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);

How to set user environment variables in Windows Server 2008 R2 as a normal user?

This can be done from the command line using the SETX command. For example to 'move' your temporary files to another disk:

SETX TEMP d:\tmp

How to update values in a specific row in a Python Pandas DataFrame?

In SQL, I would have do it in one shot as

update table1 set col1 = new_value where col1 = old_value

but in Python Pandas, we could just do this:

data = [['ram', 10], ['sam', 15], ['tam', 15]] 
kids = pd.DataFrame(data, columns = ['Name', 'Age']) 
kids

which will generate the following output :

    Name    Age
0   ram     10
1   sam     15
2   tam     15

now we can run:

kids.loc[kids.Age == 15,'Age'] = 17
kids

which will show the following output

Name    Age
0   ram     10
1   sam     17
2   tam     17

which should be equivalent to the following SQL

update kids set age = 17 where age = 15

Why can't I set text to an Android TextView?

Try Like this :

TextView text=(TextView)findViewById(R.id.textviewID);
text.setText("Text");

Instead of this:

text = (EditText) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");

MVC 4 Edit modal form using Bootstrap

In $('.editor-container').click(function (){}), shouldn't var url = "/area/controller/MyEditAction"; be var url = "/area/controller/EditPartData";?

Palindrome check in Javascript

25x faster than the standard answer

function isPalindrome(s,i) {
 return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}

use like:

isPalindrome('racecar');

as it defines "i" itself

Fiddle: http://jsfiddle.net/namcx0yf/9/

This is ~25 times faster than the standard answer below.

function checkPalindrome(str) {
  return str == str.split('').reverse().join('');
}

Fiddle: http://jsfiddle.net/t0zfjfab/2/

View console for performance results.

Although the solution is difficult to read and maintain, I would recommend understanding it to demonstrate non-branching with recursion and bit shifting to impress your next interviewer.

explained

The || and && are used for control flow like "if" "else". If something left of || is true, it just exits with true. If something is false left of || it must continue. If something left of && is false, it exits as false, if something left of a && is true, it must continue. This is considered "non-branching" as it does not need if-else interupts, rather its just evaluated.

1. Used an initializer not requiring "i" to be defined as an argument. Assigns "i" to itself if defined, otherwise initialize to 0. Always is false so next OR condition is always evaluated.

(i = i || 0) < 0

2. Checks if "i" went half way but skips checking middle odd char. Bit shifted here is like division by 2 but to lowest even neighbor division by 2 result. If true then assumes palindrome since its already done. If false evaluates next OR condition.

i >= s.length >> 1

3. Compares from beginning char and end char according to "i" eventually to meet as neighbors or neighbor to middle char. If false exits and assumes NOT palindrome. If true continues on to next AND condition.

s[i] == s[s.length-1-i]

4. Calls itself again for recursion passing the original string as "s". Since "i" is defined for sure at this point, it is pre-incremented to continue checking the string's position. Returns boolean value indicating if palindrome.

isPalindrome(s,++i)

BUT...

A simple for loop is still about twice as fast as my fancy answer (aka KISS principle)

function fastestIsPalindrome(str) {
  var len = Math.floor(str.length / 2);
  for (var i = 0; i < len; i++)
    if (str[i] !== str[str.length - i - 1])
      return false;
  return true;
}

http://jsfiddle.net/6L953awz/1/

How do I loop through children objects in javascript?

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

How to create a fixed sidebar layout with Bootstrap 4?

I used this in my code:

<div class="sticky-top h-100">
    <nav id="sidebar" class="vh-100">
        ....

this cause your sidebar height become 100% and fixed at top.

Android emulator-5554 offline

If you are on Linux or Mac, and assuming the offline device is 'emulator-5554', you can run the following:

netstat -tulpn|grep 5554

Which yields the following output:

tcp        0      0 127.0.0.1:5554          0.0.0.0:*               LISTEN      4848/emulator64-x86
tcp        0      0 127.0.0.1:5555          0.0.0.0:*               LISTEN      4848/emulator64-x86

This tells me that the process id 4848 (yours will likely be different) is still listening on port 5554. You can now kill that process with:

sudo kill -9 4848

and the ghost offline-device is no more!

Passing environment-dependent variables in webpack

I prefer using .env file for different environment.

  1. Use webpack.dev.config to copy env.dev to .env into root folder
  2. Use webpack.prod.config to copy env.prod to .env

and in code

use

require('dotenv').config(); const API = process.env.API ## which will store the value from .env file

Can HTTP POST be limitless?

Different IIS web servers can process different amounts of data in the 'header', according to this (now deleted) article; http://classicasp.aspfaq.com/forms/what-is-the-limit-on-form/post-parameters.html;

Note that there is no limit on the number of FORM elements you can pass via POST, but only on the aggregate size of all name/value pairs. While GET is limited to as low as 1024 characters, POST data is limited to 2 MB on IIS 4.0, and 128 KB on IIS 5.0. Each name/value is limited to 1024 characters, as imposed by the SGML spec. Of course this does not apply to files uploaded using enctype='multipart/form-data' ... I have had no problems uploading files in the 90 - 100 MB range using IIS 5.0, aside from having to increase the server.scriptTimeout value as well as my patience!

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

How to exclude a directory in find . command

TLDR: understand your root directories and tailor your search from there, using the -path <excluded_path> -prune -o option. Do not include a trailing / at the end of the excluded path.

Example:

find / -path /mnt -prune -o -name "*libname-server-2.a*" -print


To effectively use the find I believe that it is imperative to have a good understanding of your file system directory structure. On my home computer I have multi-TB hard drives, with about half of that content backed up using rsnapshot (i.e., rsync). Although backing up to to a physically independent (duplicate) drive, it is mounted under my system root (/) directory: /mnt/Backups/rsnapshot_backups/:

/mnt/Backups/
+-- rsnapshot_backups/
    +-- hourly.0/
    +-- hourly.1/
    +-- ...
    +-- daily.0/
    +-- daily.1/
    +-- ...
    +-- weekly.0/
    +-- weekly.1/
    +-- ...
    +-- monthly.0/
    +-- monthly.1/
    +-- ...

The /mnt/Backups/rsnapshot_backups/ directory currently occupies ~2.9 TB, with ~60M files and folders; simply traversing those contents takes time:

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find /mnt/Backups/rsnapshot_backups | wc -l
60314138    ## 60.3M files, folders
34:07.30    ## 34 min

time du /mnt/Backups/rsnapshot_backups -d 0
3112240160  /mnt/Backups/rsnapshot_backups    ## 3.1 TB
33:51.88    ## 34 min

time rsnapshot du    ## << more accurate re: rsnapshot footprint
2.9T    /mnt/Backups/rsnapshot_backups/hourly.0/
4.1G    /mnt/Backups/rsnapshot_backups/hourly.1/
...
4.7G    /mnt/Backups/rsnapshot_backups/weekly.3/
2.9T    total    ## 2.9 TB, per sudo rsnapshot du (more accurate)
2:34:54          ## 2 hr 35 min

Thus, anytime I need to search for a file on my / (root) partition, I need to deal with (avoid if possible) traversing my backups partition.


EXAMPLES

Among the approached variously suggested in this thread (How to exclude a directory in find . command), I find that searches using the accepted answer are much faster -- with caveats.

Solution 1

Let's say I want to find the system file libname-server-2.a, but I do not want to search through my rsnapshot backups. To quickly find a system file, use the exclude path /mnt (i.e., use /mnt, not /mnt/, or /mnt/Backups, or ...):

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -path /mnt -prune -o -name "*libname-server-2.a*" -print
/usr/lib/libname-server-2.a
real    0m8.644s              ## 8.6 sec  <<< NOTE!
user    0m1.669s
 sys    0m2.466s

## As regular user (victoria); I also use an alternate timing mechanism, as
## here I am using 2>/dev/null to suppress "Permission denied" warnings:

$ START="$(date +"%s")" && find 2>/dev/null / -path /mnt -prune -o \
    -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \
    TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/usr/lib/libname-server-2.a
find command took 3 sec     ## ~3 sec  <<< NOTE!

... finds that file in just a few seconds, while this take much longer (appearing to recurse through all of the "excluded" directories):

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -path /mnt/ -prune -o -name "*libname-server-2.a*" -print
find: warning: -path /mnt/ will not match anything because it ends with /.
/usr/lib/libname-server-2.a
real    33m10.658s            ## 33 min 11 sec (~231-663x slower!)
user    1m43.142s
 sys    2m22.666s

## As regular user (victoria); I also use an alternate timing mechanism, as
## here I am using 2>/dev/null to suppress "Permission denied" warnings:

$ START="$(date +"%s")" && find 2>/dev/null / -path /mnt/ -prune -o \
    -name "*libname-server-2.a*" -print; END="$(date +"%s")"; \
    TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/usr/lib/libname-server-2.a
find command took 1775 sec    ## 29.6 min

Solution 2

The other solution offered in this thread (SO#4210042) also performs poorly:

## As sudo (#), to avoid numerous "Permission denied" warnings:

time find / -name "*libname-server-2.a*" -not -path "/mnt"
/usr/lib/libname-server-2.a
real    33m37.911s            ## 33 min 38 sec (~235x slower)
user    1m45.134s
 sys    2m31.846s

time find / -name "*libname-server-2.a*" -not -path "/mnt/*"
/usr/lib/libname-server-2.a
real    33m11.208s            ## 33 min 11 sec
user    1m22.185s
 sys    2m29.962s

SUMMARY | CONCLUSIONS

Use the approach illustrated in "Solution 1"

find / -path /mnt -prune -o -name "*libname-server-2.a*" -print

i.e.

... -path <excluded_path> -prune -o ...

noting that whenever you add the trailing / to the excluded path, the find command then recursively enters (all those) /mnt/* directories -- which in my case, because of the /mnt/Backups/rsnapshot_backups/* subdirectories, additionally includes ~2.9 TB of files to search! By not appending a trailing / the search should complete almost immediately (within seconds).

"Solution 2" (... -not -path <exclude path> ...) likewise appears to recursively search through the excluded directories -- not returning excluded matches, but unnecessarily consuming that search time.


Searching within those rsnapshot backups:

To find a file in one of my hourly/daily/weekly/monthly rsnapshot backups):

$ START="$(date +"%s")" && find 2>/dev/null /mnt/Backups/rsnapshot_backups/daily.0 -name '*04t8ugijrlkj.jpg'; END="$(date +"%s")"; TIME="$((END - START))"; printf 'find command took %s sec\n' "$TIME"
/mnt/Backups/rsnapshot_backups/daily.0/snapshot_root/mnt/Vancouver/temp/04t8ugijrlkj.jpg
find command took 312 sec   ## 5.2 minutes: despite apparent rsnapshot size
                            ## (~4 GB), it is in fact searching through ~2.9 TB)

Excluding a nested directory:

Here, I want to exclude a nested directory, e.g. /mnt/Vancouver/projects/ie/claws/data/* when searching from /mnt/Vancouver/projects/:

$ time find . -iname '*test_file*'
./ie/claws/data/test_file
./ie/claws/test_file
0:01.97

$ time find . -path '*/data' -prune -o -iname '*test_file*' -print
./ie/claws/test_file
0:00.07

Aside: Adding -print at the end of the command suppresses the printout of the excluded directory:

$ find / -path /mnt -prune -o -name "*libname-server-2.a*"
/mnt
/usr/lib/libname-server-2.a

$ find / -path /mnt -prune -o -name "*libname-server-2.a*" -print
/usr/lib/libname-server-2.a

E11000 duplicate key error index in mongodb mongoose

The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address.

The relevant documentation for this:

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.

You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

unique indexes

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.

In other words, a sparse index is ok with multiple documents all having null values.

sparse indexes


From comments:

Your error says that the key is named mydb.users.$email_1 which makes me suspect that you have an index on both users.email and users.local.email (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes() if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>).

Get data from fs.readFile

you can read file by

var readMyFile = function(path, cb) {
      fs.readFile(path, 'utf8', function(err, content) {
        if (err) return cb(err, null);
        cb(null, content);
      });
    };

Adding on you can write to file,

var createMyFile = (path, data, cb) => {
  fs.writeFile(path, data, function(err) {
    if (err) return console.error(err);
    cb();
  });
};

and even chain it together

var readFileAndConvertToSentence = function(path, callback) {
  readMyFile(path, function(err, content) {
    if (err) {
      callback(err, null);
    } else {
      var sentence = content.split('\n').join(' ');
      callback(null, sentence);
    }
  });
};

LINQ - Full Outer Join

I really hate these linq expressions, this is why SQL exists:

select isnull(fn.id, ln.id) as id, fn.firstname, ln.lastname
   from firstnames fn
   full join lastnames ln on ln.id=fn.id

Create this as sql view in database and import it as entity.

Of course, (distinct) union of left and right joins will make it too, but it is stupid.

Get the Id of current table row with Jquery

First, your jQuery will not work at all unless you enclose all your trs and tds in a table:

<table>
    <tr>...</tr>
    ...
</table>

Second, your code gets the id of the first tr of the page, since you select all the trs of the page and get the id of the first one (.attr() returns the attribute of the first element in the set of elements it is used on)

Your current code:

  $('input[type=button]' ).click(function() {
   bid = (this.id) ; // button ID 
   trid = $('tr').attr('id'); // ID of the the first TR on the page
                              // $('tr') selects all trs in the DOM
  });

trid is always TEST1 (jsFiddle)


Instead of selecting all trs on the page with $('tr'), you want to select the first ancestor of the clicked upon input that is a tr. Use .closest() for this in the form $(this).closest('tr').

You can reference the clicked on element as this, make a jQuery object out of it with the form $(this), so you have access to all the jQuery methods on it.

What your code should look like:

  // On DOM ready...
$(function() {

      $('input[type=button]' ).click(function() {

          var bid, trid; // Declare variables. If you don't use var 
                         // you will bind bid and trid 
                         // to the window, since you make them global variables.

          bid = (this.id) ; // button ID 

          trid = $(this).closest('tr').attr('id'); // table row ID 
      });
});

jsFiddle example

get the value of DisplayName attribute

I have this generic utility method. I pass in a list of a given type (Assuming you have a supporting class) and it generates a datatable with the properties as column headers and the list items as data.

Just like in standard MVC, if you dont have DisplayName attribute defined, it will fall back to the property name so you only have to include DisplayName where it is different to the property name.

    public DataTable BuildDataTable<T>(IList<T> data)
    {
        //Get properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        //.Where(p => !p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal).ToArray(); //Hides virtual properties

        //Get column headers
        bool isDisplayNameAttributeDefined = false;
        string[] headers = new string[Props.Length];
        int colCount = 0;
        foreach (PropertyInfo prop in Props)
        {
            isDisplayNameAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayNameAttribute));

            if (isDisplayNameAttributeDefined)
            {
                DisplayNameAttribute dna = (DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute));
                if (dna != null)
                    headers[colCount] = dna.DisplayName;
            }
            else
                headers[colCount] = prop.Name;

            colCount++;
            isDisplayNameAttributeDefined = false;
        }

        DataTable dataTable = new DataTable(typeof(T).Name);

        //Add column headers to datatable
        foreach (var header in headers)
            dataTable.Columns.Add(header);

        dataTable.Rows.Add(headers);

        //Add datalist to datatable
        foreach (T item in data)
        {
            object[] values = new object[Props.Length];
            for (int col = 0; col < Props.Length; col++)
                values[col] = Props[col].GetValue(item, null);

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

If there's a more efficient / safer way of doing this, I'd appreicate any feedback. The commented //Where clause will filter out virtual properties. Useful if you are using model classes directly as EF puts in "Navigation" properties as virtual. However it will also filter out any of your own virtual properties if you choose to extend such classes. For this reason, I prefer to make a ViewModel and decorate it with only the needed properties and display name attributes as required, then make a list of them.

Hope this helps.

Set output of a command as a variable (with pipes)

In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:

:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"

:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Convert PDF to clean SVG?

You can use Inkscape on the commandline only, without opening a GUI. Try this:

inkscape \
  --without-gui \
  --file=input.pdf \
  --export-plain-svg=output.svg 

For a complete list of all commandline options, run inkscape --help.

What is the difference between `let` and `var` in swift?

A value can be reassigned in case of var

 //Variables
 var age = 42
 println(age) //Will print 42
 age = 90
 println(age) //Will Print 90

** the newAge constant cannot be reassigned to a new value. Trying to do so will give a compile time error**

//Constants
let newAge = 92 //Declaring a constant using let
println(newAge) //Will print 92.

How to change color and font on ListView

If u want to set background of the list then place the image before the < Textview>

< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

and if u want to change color then put color code on above textbox like this

 android:textColor="#ffffff"

Replacement for "rename" in dplyr

You can actually use plyr's rename function as part of dplyr chains. I think every function that a) takes a data.frame as the first argument and b) returns a data.frame works for chaining. Here is an example:

library('plyr')
library('dplyr')

DF = data.frame(var=1:5)

DF %>%
    # `rename` from `plyr`
    rename(c('var'='x')) %>%
    # `mutate` from `dplyr` (note order in which libraries are loaded)
    mutate(x.sq=x^2)

#   x x.sq
# 1 1    1
# 2 2    4
# 3 3    9
# 4 4   16
# 5 5   25

UPDATE: The current version of dplyr supports renaming directly as part of the select function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr chains is still valid though and rename is an interesting example.

Apply global variable to Vuejs

In your main.js file, you have to import Vue like this :

import Vue from 'vue'

Then you have to declare your global variable in the main.js file like this :

Vue.prototype.$actionButton = 'Not Approved'

If you want to change the value of the global variable from another component, you can do it like this :

Vue.prototype.$actionButton = 'approved'

https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example

Cannot call getSupportFragmentManager() from activity

Instead of

extends Fragment

use

extends android.support.v4.app.Fragment 

This works for me. for *API14 and above

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

How to Parse JSON Array with Gson

in Kotlin :

val jsonArrayString = "['A','B','C']"

val gson = Gson()

val listType: Type = object : TypeToken<List<String?>?>() {}.getType()

val stringList : List<String> = gson.fromJson(
                            jsonArrayString,
                            listType)

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Android - shadow on text?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="20dp" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:shadowColor="#000"
        android:shadowDx="0"
        android:shadowDy="0"
        android:shadowRadius="50"
        android:text="Text Shadow Example1"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Text Shadow Example2"
        android:textColor="#FBFBFB"
        android:textSize="28dp"
        android:textStyle="bold" />

</LinearLayout>

In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are

android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right

android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.

android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color


Shadow Effect on Android TextView pragmatically

Use below code snippet to get the shadow effect on the second TextView pragmatically.

TextView textv = (TextView) findViewById(R.id.textview2);
textv.setShadowLayer(30, 0, 0, Color.RED);        

Output :

enter image description here

Specifying Style and Weight for Google Fonts

Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:

Thin            100     
Extra Light     200
Light           300
Regular         400
Medium          500
Semi-Bold       600
Bold            700
Extra-Bold      800
Black           900

Note that very few fonts come in all 9 weights.

SQL Server : GROUP BY clause to get comma-separated values

try this:

SELECT ReportId, Email = 
    STUFF((SELECT ', ' + Email
           FROM your_table b 
           WHERE b.ReportId = a.ReportId 
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId


SQL fiddle demo

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;
}

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

http://jsfiddle.net/weaversnap/7FqsX/1/

How do you synchronise projects to GitHub with Android Studio?

On Android Studio 1.0.2 you only need to go VCS-> Import into Version control -> Share Project on GitHub.

Pop up will appear asking for the repo name.

Support for the experimental syntax 'classProperties' isn't currently enabled

I find the problem that my .babelrc was ignored, However I create babel.config.js and add the following:

module.exports = {
  plugins: [
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-transform-regenerator',
    [
      '@babel/plugin-transform-runtime',
      {
        helpers: false,
        regenerator: true,
      },
    ],
  ],
  presets: [
    "@babel/preset-flow",
    'module:metro-react-native-babel-preset',
  ],
};

And it works for me on React Native application, I think this also would help React apps as well.

Responsive iframe using Bootstrap

The best solution that worked great for me.

You have to: Copy this code to your main CSS file,

.responsive-video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 60px; overflow: hidden;
}

.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

and then put your embeded video to

<div class="responsive-video">
    <iframe ></iframe>
</div>

That’s it! Now you can use responsive videos on your site.

Font Awesome not working, icons showing as squares

Use this

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

I had similar issue with Amazon Cloudfront CDN but it got resolved after I started loading it from maxcdn

How to compare two dates along with time in java

An alternative is Joda-Time.

Use DateTime

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();

Is it possible to run selenium (Firefox) web driver without a GUI?

An optional is to use pyvirtualdisplay like this:

from pyvirtualdisplay import Display

display = Display(visible=0, size=[800, 600])
display.start()

#do selenium job here

display.close()

A shorter version is:

with Display() as display:
    # selenium job here

This is generally a python encapsulate of xvfb, and more convinient somehow.

By the way, although PhantomJS is a headless browser and no window will be open if you use it, it seems that PhantomJS still needs a gui environment to work.

I got Error Code -6 when I use PhantomJS() instead of Firefox() in headless mode (putty-connected console). However everything is ok in desktop environment.

Adding a Method to an Existing Object Instance

You can use lambda to bind a method to an instance:

def run(self):
    print self._instanceString

class A(object):
    def __init__(self):
        self._instanceString = "This is instance string"

a = A()
a.run = lambda: run(a)
a.run()

Output:

This is instance string

Submit HTML form on self page

In 2013, with all the HTML5 stuff, you can just omit the 'action' attribute to self-submit a form

<form>

Actually, the Form Submission subsection of the current HTML5 draft does not allow action="" (empty attribute). It is against the specification.

From this other Stack Overflow answer.

How do I supply an initial value to a text field?

You can use a TextFormField instead of TextField, and use the initialValue property. for example

TextFormField(initialValue: "I am smart")

How to terminate a python subprocess launched with shell=True

Send the signal to all the processes in group

    self.proc = Popen(commands, 
            stdout=PIPE, 
            stderr=STDOUT, 
            universal_newlines=True, 
            preexec_fn=os.setsid)

    os.killpg(os.getpgid(self.proc.pid), signal.SIGHUP)
    os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

Finding Key associated with max Value in a Java Map

Java 8 way to get all keys with max value.

Integer max = PROVIDED_MAP.entrySet()
            .stream()
            .max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1)
            .get()
            .getValue();

List listOfMax = PROVIDED_MAP.entrySet()
            .stream()
            .filter(entry -> entry.getValue() == max)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

System.out.println(listOfMax);

Also you can parallelize it by using parallelStream() instead of stream()

Limit number of characters allowed in form input text field

<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

<script>
function checkNumber(key) {
  console.log(key);
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  }
  else {
    key.preventDefault();
  }
}
</script>

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

How do I catch an Ajax query post error?

You have to log the responseText:

$.ajax({
    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
  }
})
.done(
 function (data) {
  //your code
 }
)
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );
})

Barcode scanner for mobile phone for Website in form

Scandit is a startup whose goal is to replace bulky, expensive laser barcode scanners with cheap mobile phones.

There are SDKs for Android, iOS, Windows, C API/Linux, React Native, Cordova/PhoneGap, Xamarin.

There is also Scandit Barcode Scanner SDK for the Web which the WebAssembly version of the SDK. It runs in modern browsers, also on phones.

There's a client library that also provides a barcode picker component. It can be used like this:

<div id="barcode-picker" style="max-width: 1280px; max-height: 80%;"></div>

<script src="https://unpkg.com/scandit-sdk"></script>
<script>
    console.log('Loading...');
    ScanditSDK.configure("xxx", {
engineLocation: "https://unpkg.com/scandit-sdk/build/"
    }).then(() => {
      console.log('Loaded');
      ScanditSDK.BarcodePicker.create(document.getElementById('barcode-picker'), {
        playSoundOnScan: true,
        vibrateOnScan: true
      }).then(function(barcodePicker) {
        console.log("Ready");
        barcodePicker.applyScanSettings(new ScanditSDK.ScanSettings({
          enabledSymbologies: ["ean8", "ean13", "upca", "upce", "code128", "code39", "code93", "itf", "qr"],
          codeDuplicateFilter: 1000
        }));
        barcodePicker.onScan(function(barcodes) {
          console.log(barcodes);
        });
      });
    });
</script>

Disclaimer: I work for Scandit

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Python Timezone conversion

Using pytz

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"
timezonelist = ['UTC','US/Pacific','Europe/Berlin']
for zone in timezonelist:

    now_time = datetime.now(timezone(zone))
    print now_time.strftime(fmt)

jQuery scroll() detect when user stops scrolling

For those Who Still Need This Here Is The Solution

_x000D_
_x000D_
  $(function(){_x000D_
      var t;_x000D_
      document.addEventListener('scroll',function(e){_x000D_
          clearTimeout(t);_x000D_
          checkScroll();_x000D_
      });_x000D_
      _x000D_
      function checkScroll(){_x000D_
          t = setTimeout(function(){_x000D_
             alert('Done Scrolling');_x000D_
          },500); /* You can increase or reduse timer */_x000D_
      }_x000D_
  });
_x000D_
_x000D_
_x000D_

How to programmatically take a screenshot on Android?

If you want to take screenshot from fragment than follow this:

  1. Override onCreateView():

             @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                // Inflate the layout for this fragment
                View view = inflater.inflate(R.layout.fragment_one, container, false);
                mView = view;
            }
    
  2. Logic for taking screenshot:

     button.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         View view =  mView.findViewById(R.id.scrollView1);
          shareScreenShotM(view, (NestedScrollView) view); 
     }
    
  3. method shareScreenShotM)():

    public void shareScreenShotM(View view, NestedScrollView scrollView){
    
         bm = takeScreenShot(view,scrollView);  //method to take screenshot
        File file = savePic(bm);  // method to save screenshot in phone.
        }
    
  4. method takeScreenShot():

             public Bitmap takeScreenShot(View u, NestedScrollView z){
    
                u.setDrawingCacheEnabled(true);
                int totalHeight = z.getChildAt(0).getHeight();
                int totalWidth = z.getChildAt(0).getWidth();
    
                Log.d("yoheight",""+ totalHeight);
                Log.d("yowidth",""+ totalWidth);
                u.layout(0, 0, totalWidth, totalHeight);
                u.buildDrawingCache();
                Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
                u.setDrawingCacheEnabled(false);
                u.destroyDrawingCache();
                 return b;
            }
    
  5. method savePic():

     public static File savePic(Bitmap bm){
    
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
             File sdCardDirectory =  new File(Environment.getExternalStorageDirectory() + "/Foldername");
    
           if (!sdCardDirectory.exists()) {
                sdCardDirectory.mkdirs();
          }
           //  File file = new File(dir, fileName);
          try {
             file = new File(sdCardDirectory, Calendar.getInstance()
                .getTimeInMillis() + ".jpg");
            file.createNewFile();
            new FileOutputStream(file).write(bytes.toByteArray());
            Log.d("Fabsolute", "File Saved::--->" + file.getAbsolutePath());
             Log.d("Sabsolute", "File Saved::--->" + sdCardDirectory.getAbsolutePath());
         } catch (IOException e) {
              e.printStackTrace();
          }
         return file;
       }
    

For activity you can simply use View v1 = getWindow().getDecorView().getRootView(); instead of mView

How to get and set the current web page scroll position?

The currently accepted answer is incorrect - document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

To get the current position, you want:

document.documentElement.scrollTop || document.body.scrollTop

You can set the current position to 1000px down the page like so:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

Or, using jQuery (animate it while you're at it!):

$("html, body").animate({ scrollTop: "1000px" });

How do detect Android Tablets in general. Useragent?

The 51Degrees beta, 1.0.1.6 and the latest stable release 1.0.2.2 (4/28/2011) now have the ability to sniff for tablet. Basically along the lines of:

string capability = Request.Browser["is_tablet"];

Hope this helps you.

How do you clone a Git repository into a specific folder?

The example I think a lot of people asking this question are after is this. If you are in the directory you want the contents of the git repository dumped to, run:

git clone [email protected]:whatever .

The "." at the end specifies the current folder as the checkout folder.

Remove characters from C# string

Its a powerful method I usually use in the same case:

private string Normalize(string text)
{
        return string.Join("",
            from ch in text
            where char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)
            select ch);
}

Enjoy...

How can I set up an editor to work with Git on Windows?

It seems as if Git won't find the editor if there are spaces in the path. So you will have to put the batch file mentioned in Patrick's answer into a non-whitespace path.

Using ffmpeg to change framerate

To the best of my knowledge you can't do this with ffmpeg without re-encoding. I had a 24fps file I wanted at 25fps to match some other material I was working with. I used the command ffmpeg -i inputfile -r 25 outputfile which worked perfectly with a webm,matroska input and resulted in an h264, matroska output utilizing encoder: Lavc56.60.100

You can accomplish the same thing at 6fps but as you noted the duration will not change (which in most cases is a good thing as otherwise you will lose audio sync). If this doesn't fit your requirements I suggest that you try this answer although my experience has been that it still re-encodes the output file.

For the best frame accuracy you are still better off decoding to raw streams as previously suggested. I use a script for this as reproduced below:

#!/bin/bash
#This script will decompress all files in the current directory, video to huffyuv and audio to PCM
#unsigned 8-bit and place the output #in an avi container to ease frame accurate editing.
for f in *
do
ffmpeg -i "$f" -c:v huffyuv -c:a pcm_u8 "$f".avi
done

Clearly this script expects all files in the current directory to be media files but can easily be changed to restrict processing to a specific extension of your choosing. Be aware that your file size will increase by a rather large factor when you decompress into raw streams.

How to make python Requests work via socks proxy

The modern way:

pip install -U requests[socks]

then

import requests

resp = requests.get('http://go.to', 
                    proxies=dict(http='socks5://user:pass@host:port',
                                 https='socks5://user:pass@host:port'))

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

How to add Android Support Repository to Android Studio?

Instead of doing this:

compile "com.android.support:support-v4:18.0.+"

Do this:

compile 'com.android.support:support-v4:18.0.+' 

Worked for me

How to keep form values after post

you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.

Serialize Class containing Dictionary member

You can't serialize a class that implements IDictionary. Check out this link.

Q: Why can't I serialize hashtables?

A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

So I think you need to create your own version of the Dictionary for this. Check this other question.

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

JavaScript property access: dot notation vs. brackets?

You have to use square bracket notation when -

  1. The property name is number.

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  2. The property name has special character.

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  3. The property name is assigned to a variable and you want to access the property value by this variable.

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    

How can I define a composite primary key in SQL?

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

UTF-8 text is garbled when form is posted as multipart/form-data

The filter is key for IE. A few other things to check;

What is the page encoding and character set? Both should be UTF-8

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

What is the character set in the meta tag?

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Does your MySQL connection string specify UTF-8? e.g.

jdbc:mysql://127.0.0.1/dbname?requireSSL=false&useUnicode=true&characterEncoding=UTF-8

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

Converting Integer to String with comma for thousands

You ask for quickest, but perhaps you mean "best" or "correct" or "typical"?

You also ask for commas to indicate thousands, but perhaps you mean "in normal human readable form according to the local custom of your user"?

You do it as so:

    int i = 35634646;
    String s = NumberFormat.getIntegerInstance().format(i);

Americans will get "35,634,646"

Germans will get "35.634.646"

Swiss Germans will get "35'634'646"

How to find the users list in oracle 11g db?

I tried this query and it works for me.

SELECT username FROM dba_users 
ORDER BY username;

If you want to get the list of all that users which are created by end-user, then you can try this:

SELECT username FROM dba_users where Default_TableSpace not in ('SYSAUX', 'SYSTEM', 'USERS')
ORDER BY username;

In Chrome 55, prevent showing Download button for HTML 5 video

May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)

They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.

Can a java lambda have more than 1 parameter?

It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)

@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}

I've called it Function6 here. The name is at your discretion, just try not to clash with existing names in the Java libraries.


There's also no way to define a variable number of type parameters, if that's what you were asking about.


Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.

How to improve Netbeans performance?

  • Download the latest Netbeans
  • Remove all the plugins you don't need.
  • Use the latest version of Java

Create folder with batch but only if it doesn't already exist

Just call mkdir C:\VTS no matter what. It will simply report that the subdirectory already exists.

Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.

Using StringWriter for XML Serialization

First of all, beware of finding old examples. You've found one that uses XmlTextWriter, which is deprecated as of .NET 2.0. XmlWriter.Create should be used instead.

Here's an example of serializing an object into an XML column:

public void SerializeToXmlColumn(object obj)
{
    using (var outputStream = new MemoryStream())
    {
        using (var writer = XmlWriter.Create(outputStream))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(writer, obj);
        }

        outputStream.Position = 0;
        using (var conn = new SqlConnection(Settings.Default.ConnectionString))
        {
            conn.Open();

            const string INSERT_COMMAND = @"INSERT INTO XmlStore (Data) VALUES (@Data)";
            using (var cmd = new SqlCommand(INSERT_COMMAND, conn))
            {
                using (var reader = XmlReader.Create(outputStream))
                {
                    var xml = new SqlXml(reader);

                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Data", xml);
                    cmd.ExecuteNonQuery();
                }
            }
        }
    }
}