Programs & Examples On #Wcf rest

A REST service built with WCF

Cannot set content-type to 'application/json' in jQuery.ajax

So all you need to do for this to work is add:

headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

as a field to your post request and it'll work.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

How to change color of Toolbar back button in Android?

I did it this way using the Material Components library:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
</style>

<style name="AppTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>

Rounding numbers to 2 digits after comma

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);

Draw line in UIView

You can user UIBezierPath Class for this:

And can draw as many lines as you want:

I have subclassed UIView :

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

And initialized the pathArray and dictPAth objects which will be used for line drawing. I am writing the main portion of the code from my own project:

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

touchesBegin method :

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

touchesMoved Method:

UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

touchesEnded Method:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];

Select rows where column is null

Do you mean something like:

SELECT COLUMN1, COLUMN2 FROM MY_TABLE WHERE COLUMN1 = 'Value' OR COLUMN1 IS NULL

?

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

How can I listen to the form submit event in javascript?

With jQuery:

$('form').submit(function () {
    // Validate here

    if (pass)
        return true;
    else
        return false;
});

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

How to customize the configuration file of the official PostgreSQL Docker image?

I looked through all answers and there is another option left. You can change your CMD value in docker file (it is not the best one, but still possible way to achieve your goal).

Basically we need to

  • Copy config file in docker container
  • Override postgres start options

Docker file example:

FROM postgres:9.6
USER postgres

# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql

# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Though I think using command: postgres -c config_file=/etc/postgresql/postgresql.confin your docker-compose.yml file proposed by Matthias Braun is the best option.

How to check if a Constraint exists in Sql server?

IF (OBJECT_ID('FK_ChannelPlayerSkins_Channels') IS NOT NULL)

HTML Form: Select-Option vs Datalist-Option

I noticed that there is no selected feature in datalist. It only gives you choice but can't have a default option. You can't show the selected option on the next page either.

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

CSS ''background-color" attribute not working on checkbox inside <div>

A checkbox does not have background color.

But to add the effect, you may wrap each checkbox with a div that has color:

<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>
<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>

Is this how you define a function in jQuery?

No, you can just write the function as:

$(document).ready(function() {
    MyBlah("hello");
});

function MyBlah(blah) {
    alert(blah);
}

This calls the function MyBlah on content ready.

Use JAXB to create Object from XML String

There is no unmarshal(String) method. You should use a Reader:

Person person = (Person) unmarshaller.unmarshal(new StringReader("xml string"));

But usually you are getting that string from somewhere, for example a file. If that's the case, better pass the FileReader itself.

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

Build Android Studio app via command line

note, you can also do this within Android Studio by clicking the gradle window, and then the 'elephant' button. This will open a new window called "run anything" (can also be found by searching for that name in 'search everywhere') where you can manually type any gradle command you want in. Not "quite" command line, but often provides more of what I need than windows command line.

This allows you to give optional params to gradle tasks, etc.

Creating a recursive method for Palindrome

there's no code smaller than this:

public static boolean palindrome(String x){
    return (x.charAt(0) == x.charAt(x.length()-1)) && 
        (x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}

if you want to check something:

public static boolean palindrome(String x){
    if(x==null || x.length()==0){
        throw new IllegalArgumentException("Not a valid string.");
    }
    return (x.charAt(0) == x.charAt(x.length()-1)) && 
        (x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}

LOL B-]

Error "The input device is not a TTY"

Remove the -it from your cli to make it non interactive and remove the TTY. If you don't need either, e.g. running your command inside of a Jenkins or cron script, you should do this.

Or you can change it to -i if you have input piped into the docker command that doesn't come from a TTY. If you have something like xyz | docker ... or docker ... <input in your command line, do this.

Or you can change it to -t if you want TTY support but don't have it available on the input device. Do this for apps that check for a TTY to enable color formatting of the output in your logs, or for when you later attach to the container with a proper terminal.

Or if you need an interactive terminal and aren't running in a terminal on Linux or MacOS, use a different command line interface. PowerShell is reported to include this support on Windows.


What is a TTY? It's a terminal interface that supports escape sequences, moving the cursor around, etc, that comes from the old days of dumb terminals attached to mainframes. Today it is provided by the Linux command terminals and ssh interfaces. See the wikipedia article for more details.

To see the difference of running a container with and without a TTY, run a container without one: docker run --rm -i ubuntu bash. From inside that container, install vim with apt-get update; apt-get install vim. Note the lack of a prompt. When running vim against a file, try to move the cursor around within the file.

wildcard * in CSS for classes

Yes you can do this.

*[id^='term-']{
    [css here]
}

This will select all ids that start with 'term-'.

As for the reason for not doing this, I see where it would be preferable to select this way; as for style, I wouldn't do it myself, but it's possible.

Getting RAW Soap Data from a Web Reference Client running in ASP.net

I would prefer to have the framework do the logging for you by hooking in a logging stream which logs as the framework processes that underlying stream. The following isn't as clean as I would like it, since you can't decide between request and response in the ChainStream method. The following is how I handle it. With thanks to Jon Hanna for the overriding a stream idea

public class LoggerSoapExtension : SoapExtension
{
    private static readonly string LOG_DIRECTORY = ConfigurationManager.AppSettings["LOG_DIRECTORY"];
    private LogStream _logger;

    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return null;
    }
    public override object GetInitializer(Type serviceType)
    {
        return null;
    }
    public override void Initialize(object initializer)
    {
    }
    public override System.IO.Stream ChainStream(System.IO.Stream stream)
    {
        _logger = new LogStream(stream);
        return _logger;
    }
    public override void ProcessMessage(SoapMessage message)
    {
        if (LOG_DIRECTORY != null)
        {
            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    _logger.Type = "request";
                    break;
                case SoapMessageStage.AfterSerialize:
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    _logger.Type = "response";
                    break;
                case SoapMessageStage.AfterDeserialize:
                    break;
            }
        }
    }
    internal class LogStream : Stream
    {
        private Stream _source;
        private Stream _log;
        private bool _logSetup;
        private string _type;

        public LogStream(Stream source)
        {
            _source = source;
        }
        internal string Type
        {
            set { _type = value; }
        }
        private Stream Logger
        {
            get
            {
                if (!_logSetup)
                {
                    if (LOG_DIRECTORY != null)
                    {
                        try
                        {
                            DateTime now = DateTime.Now;
                            string folder = LOG_DIRECTORY + now.ToString("yyyyMMdd");
                            string subfolder = folder + "\\" + now.ToString("HH");
                            string client = System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.UserHostAddress != null ? System.Web.HttpContext.Current.Request.UserHostAddress : string.Empty;
                            string ticks = now.ToString("yyyyMMdd'T'HHmmss.fffffff");
                            if (!Directory.Exists(folder))
                                Directory.CreateDirectory(folder);
                            if (!Directory.Exists(subfolder))
                                Directory.CreateDirectory(subfolder);
                            _log = new FileStream(new System.Text.StringBuilder(subfolder).Append('\\').Append(client).Append('_').Append(ticks).Append('_').Append(_type).Append(".xml").ToString(), FileMode.Create);
                        }
                        catch
                        {
                            _log = null;
                        }
                    }
                    _logSetup = true;
                }
                return _log;
            }
        }
        public override bool CanRead
        {
            get
            {
                return _source.CanRead;
            }
        }
        public override bool CanSeek
        {
            get
            {
                return _source.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return _source.CanWrite;
            }
        }

        public override long Length
        {
            get
            {
                return _source.Length;
            }
        }

        public override long Position
        {
            get
            {
                return _source.Position;
            }
            set
            {
                _source.Position = value;
            }
        }

        public override void Flush()
        {
            _source.Flush();
            if (Logger != null)
                Logger.Flush();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _source.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _source.SetLength(value);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            count = _source.Read(buffer, offset, count);
            if (Logger != null)
                Logger.Write(buffer, offset, count);
            return count;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _source.Write(buffer, offset, count);
            if (Logger != null)
                Logger.Write(buffer, offset, count);
        }
        public override int ReadByte()
        {
            int ret = _source.ReadByte();
            if (ret != -1 && Logger != null)
                Logger.WriteByte((byte)ret);
            return ret;
        }
        public override void Close()
        {
            _source.Close();
            if (Logger != null)
                Logger.Close();
            base.Close();
        }
        public override int ReadTimeout
        {
            get { return _source.ReadTimeout; }
            set { _source.ReadTimeout = value; }
        }
        public override int WriteTimeout
        {
            get { return _source.WriteTimeout; }
            set { _source.WriteTimeout = value; }
        }
    }
}
[AttributeUsage(AttributeTargets.Method)]
public class LoggerSoapExtensionAttribute : SoapExtensionAttribute
{
    private int priority = 1;
    public override int Priority
    {
        get
        {
            return priority;
        }
        set
        {
            priority = value;
        }
    }
    public override System.Type ExtensionType
    {
        get
        {
            return typeof(LoggerSoapExtension);
        }
    }
}

Why is this jQuery click function not working?

You have to wrap your Javascript-Code with $(document).ready(function(){});Look this JSfiddle.

JS Code:

$(document).ready(function() {

    $("#clicker").click(function () {
        alert("Hello!");
        $(".hide_div").hide();    
    });
});

AngularJS - Building a dynamic table based on a json

<table class="table table-striped table-condensed table-hover">
    <thead>
    <tr>
        <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
        <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
    </tr>
    </tbody>
    <tfoot>

    </tfoot>
</table>

refer this https://gist.github.com/ebellinger/4399082

Adding hours to JavaScript Date object?

If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:

_x000D_
_x000D_
//JS
function addHoursToDate(date, hours) {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

//TS
function addHoursToDate(date: Date, hours: number): Date {
  return new Date(new Date(date).setHours(date.getHours() + hours));
}

let myDate = new Date();

console.log(myDate)
console.log(addHoursToDate(myDate,2))
_x000D_
_x000D_
_x000D_

SQL Error: ORA-00933: SQL command not properly ended

Oracle does not allow joining tables in an UPDATE statement. You need to rewrite your statement with a co-related sub-select

Something like this:

UPDATE system_info
SET field_value = 'NewValue' 
WHERE field_desc IN (SELECT role_type 
                     FROM system_users 
                     WHERE user_name = 'uname')

For a complete description on the (valid) syntax of the UPDATE statement, please read the manual:

http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10008.htm#i2067715

must appear in the GROUP BY clause or be used in an aggregate function

I recently run into this problem, when trying to count using case when, and found that changing the order of the which and count statements fixes the problem:

SELECT date(dateday) as pick_day,
COUNT(CASE WHEN (apples = 'TRUE' OR oranges 'TRUE') THEN fruit END)  AS fruit_counter

FROM pickings

GROUP BY 1

Instead of using - in the latter, where I got errors that apples and oranges should appear in aggregate functions

CASE WHEN ((apples = 'TRUE' OR oranges 'TRUE') THEN COUNT(*) END) END AS fruit_counter

What does the term "canonical form" or "canonical representation" in Java mean?

Wikipedia points to the term Canonicalization.

A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

The Unicode example made the most sense to me:

Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.

In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.

Failed to serialize the response in Web API with Json

I don't like this code:

foreach(var user in db.Users)

As an alternative, one might do something like this, which worked for me:

var listOfUsers = db.Users.Select(r => new UserModel
                         {
                             userModel.FirstName = r.FirstName;
                             userModel.LastName = r.LastName;

                         });

return listOfUsers.ToList();

However, I ended up using Lucas Roselli's solution.

Update: Simplified by returning an anonymous object:

var listOfUsers = db.Users.Select(r => new 
                         {
                             FirstName = r.FirstName;
                             LastName = r.LastName;
                         });

return listOfUsers.ToList();

Get DataKey values in GridView RowCommand

I managed to get the value of the DataKeys using this code:

In the GridView I added:

DataKeyNames="ID" OnRowCommand="myRowCommand"

Then in my row command function:

protected void myRowCommand(object sender, GridViewCommandEventArgs e) 
{
    LinkButton lnkBtn = (LinkButton)e.CommandSource;    // the button
    GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent;  // the row
    GridView myGrid = (GridView)sender; // the gridview
    string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey 

    switch (e.CommandName)
    {
      case "cmd1":
      // do something using the ID
      break;
      case "cmd2":
      // do something else using the ID
      break;
    }
 }

Check if decimal value is null

Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).

Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue

Rails: select unique values from a column

You can use the following Gem: active_record_distinct_on

Model.distinct_on(:rating)

Yields the following query:

SELECT DISTINCT ON ( "models"."rating" ) "models".* FROM "models"

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

This is the solution i found.

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

Configure DBContext via AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

Selenium WebDriver.get(url) does not open the URL

I had the same problem but with Chrome.

Solved it using the following steps

  1. Install Firefox/Chrome webdriver from Google
  2. Put the webdriver in Chrome's directory.

Here's the code and it worked fine

from selenium import webdriver

class InstaBot(object):
    def __init__(self):
        self.driver=webdriver.Chrome("C:\Program 
        Files(x86)\Google\Chrome\Application\chromedriver.exe")# make sure 
                                                      #it is chrome driver 
        self.driver.get("https://www.wikipedia.com")
        
        
InstaBot()

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

How to create an email form that can send email using html

You can't, the only things you can do with html is open your default email application. You must use a server code to send an email, php, asp .net....

Xcode 9 Swift Language Version (SWIFT_VERSION)

This Solution works when nothing else works:

I spent more than a week to convert the whole project and came to a solution below:

First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.

Go to Project Directory in the Terminal and Type:

pod deintegrate

This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.

Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.

So to remove those errors you have two options:

  1. Comment down all the code you have used from cocoapods library.
  2. Create a wrapper class which has dummy methods similar to cocopods library, and then call it.

Once all the errors get removed you can convert the code to the latest swift version.

Sometimes if you are getting weird errors then try cleaning derived data and try again.

Understanding generators in Python

It helps to make a clear distinction between the function foo, and the generator foo(n):

def foo(n):
    yield n
    yield n+1

foo is a function. foo(6) is a generator object.

The typical way to use a generator object is in a loop:

for n in foo(6):
    print(n)

The loop prints

# 6
# 7

Think of a generator as a resumable function.

yield behaves like return in the sense that values that are yielded get "returned" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement.

Behind the scenes, when you call bar=foo(6) the generator object bar is defined for you to have a next attribute.

You can call it yourself to retrieve values yielded from foo:

next(bar)    # Works in Python 2.6 or Python 3.x
bar.next()   # Works in Python 2.5+, but is deprecated. Use next() if possible.

When foo ends (and there are no more yielded values), calling next(bar) throws a StopInteration error.

Debugging with Android Studio stuck at "Waiting For Debugger" forever

This problem occurs when you open more than one instance of Android studio, so you need to attach the debugger manually like mentioned above.

You may need to close other instances of Android studio.

wget ssl alert handshake failure

You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).

Run this command after having installed Chocolatey (as Administrator):

choco install wget

How to keep two folders automatically synchronized?

I use this free program to synchronize local files and directories: https://github.com/Fitus/Zaloha.sh. The repository contains a simple demo as well.

The good point: It is a bash shell script (one file only). Not a black box like other programs. Documentation is there as well. Also, with some technical talents, you can "bend" and "integrate" it to create the final solution you like.

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

How do I remove javascript validation from my eclipse project?

Another reason could be that you acidentically added a Javascript nature to your project unintentionally (i just did this by accident) which enables javascript error checking.

removing this ....javascriptnature from your project fixes that.

(this is ofcourse only if you dont want eclipse to realise you have any JS)

Comparing floating point number to zero

If you are only interested in +0.0 and -0.0, you can use fpclassify from <cmath>. For instance:

if( FP_ZERO == fpclassify(x) ) do_something;

How to catch and print the full exception traceback without halting/exiting the program?

To get the precise stack trace, as a string, that would have been raised if no try/except were there to step over it, simply place this in the except block that catches the offending exception.

desired_trace = traceback.format_exc(sys.exc_info())

Here's how to use it (assuming flaky_func is defined, and log calls your favorite logging system):

import traceback
import sys

try:
    flaky_func()
except KeyboardInterrupt:
    raise
except Exception:
    desired_trace = traceback.format_exc(sys.exc_info())
    log(desired_trace)

It's a good idea to catch and re-raise KeyboardInterrupts, so that you can still kill the program using Ctrl-C. Logging is outside the scope of the question, but a good option is logging. Documentation for the sys and traceback modules.

Linux: Which process is causing "device busy" when doing umount?

Filesystems mounted on the filesystem you're trying to unmount can cause the target is busy error in addition to any files that are in use. (For example when you mount -o bind /dev /mnt/yourmount/dev in order to use chroot there.)

To find which file systems are mounted on the filesystem run the following:

mount | grep '/mnt/yourmount'

To find which files are in use the advice already suggested by others here:

lsof | grep '/mnt/yourmount'

Error handling in Bash

I prefer something really easy to call. So I use something that looks a little complicated, but is easy to use. I usually just copy-and-paste the code below into my scripts. An explanation follows the code.

#This function is used to cleanly exit any script. It does this displaying a
# given error message, and exiting with an error code.
function error_exit {
    echo
    echo "$@"
    exit 1
}
#Trap the killer signals so that we can exit with a good message.
trap "error_exit 'Received signal SIGHUP'" SIGHUP
trap "error_exit 'Received signal SIGINT'" SIGINT
trap "error_exit 'Received signal SIGTERM'" SIGTERM

#Alias the function so that it will print a message with the following format:
#prog-name(@line#): message
#We have to explicitly allow aliases, we do this because they make calling the
#function much easier (see example).
shopt -s expand_aliases
alias die='error_exit "Error ${0}(@`echo $(( $LINENO - 1 ))`):"'

I usually put a call to the cleanup function in side the error_exit function, but this varies from script to script so I left it out. The traps catch the common terminating signals and make sure everything gets cleaned up. The alias is what does the real magic. I like to check everything for failure. So in general I call programs in an "if !" type statement. By subtracting 1 from the line number the alias will tell me where the failure occurred. It is also dead simple to call, and pretty much idiot proof. Below is an example (just replace /bin/false with whatever you are going to call).

#This is an example useage, it will print out
#Error prog-name (@1): Who knew false is false.
if ! /bin/false ; then
    die "Who knew false is false."
fi

How can I get a favicon to show up in my django app?

        <link rel="shortcut icon" type="image/png" href="{% static 'favicon/sample.png' %}" />

Also run: python manage.py collectstatic

How to read a CSV file into a .NET Datatable

The best option I have found, and it resolves issues where you may have different versions of Office installed, and also 32/64-bit issues like Chuck Bevitt mentioned, is FileHelpers.

It can be added to your project references using NuGet and it provides a one-liner solution:

CommonEngine.CsvToDataTable(path, "ImportRecord", ',', true);

How to use UTF-8 in resource properties with ResourceBundle

look at this : http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)

the properties accept an Reader object as arguments, which you can create from an InputStream.

at the create time, you can specify the encoding of the Reader:

InputStreamReader isr = new InputStreamReader(stream, "UTF-8");

then apply this Reader to the load method :

prop.load(isr);

BTW: get the stream from .properties file :

 InputStream stream = this.class.getClassLoader().getResourceAsStream("a.properties");

BTW: get resource bundle from InputStreamReader:

ResourceBundle rb = new PropertyResourceBundle(isr);

hope this can help you !

How to open CSV file in R when R says "no such file or directory"?

Here is one way to do it. It uses the ability of R to construct file paths based on the platform and hence will work on both Mac OS and Windows. Moreover, you don't need to convert your xls file to csv, as there are many R packages that will help you read xls directly (e.g. gdata package).

# get user's home directory
home = setwd(Sys.getenv("HOME"));

# construct path to file
fpath = file.path(home, "Desktop", "RTrial.xls");

# load gdata library to read xls files
library(gdata);

# read xls file
Rtrial = read.xls(fpath);

Let me know if this works.

How to restart a node.js server

I understand that my comment relate with windows, but may be someone be useful. For win run in cmd:

wmic process  where "commandline like '%my_app.js%' AND name='node.exe' " CALL Terminate

then you can run your app again:

node my_app.js

Also you can use it in batch file, with escape quotes:

wmic process  where "commandline like '%%my_app.js%%' AND name='node.exe' " CALL Terminate
node my_app.js

Converting String to Double in Android

  kw=(EditText)findViewById(R.id.kw);
    btn=(Button)findViewById(R.id.btn);
    cost=(TextView )findViewById(R.id.cost);


            btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;
            cost.setText(cst.toString());
        }
    });

Getting command-line password input in Python

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.

Delete commits from a branch in Git

If you want to keep the history, showing the commit and the revert, you should use:

git revert GIT_COMMIT_HASH

enter the message explaining why are you reverting and then:

git push  

When you issue git log you'll see both the "wrong" commit and revert log messages.

Debugging "Element is not clickable at point" error

I was facing the same problem with clj-webdriver (clojure port of Selenium). I just translated the previous solution to clojure for convenience. You can call this function before doing click or whatever to avoid that problem.

(defn scrollTo
  "Scrolls to the position of the given css selector if found"
  [q]
  (if (exists? q) 
    (let [ loc (location-once-visible q) jscript (str "window.scrollTo(" (:x loc) "," (:y loc) ")") ] 
      (execute-script jscript))))

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

"Unable to locate tools.jar" when running ant

The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.

I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.

Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin appears).

How to extract base URL from a string in JavaScript?

WebKit-based browsers, Firefox as of version 21 and current versions of Internet Explorer (IE 10 and 11) implement location.origin.

location.origin includes the protocol, the domain and optionally the port of the URL.

For example, location.origin of the URL http://www.sitename.com/article/2009/09/14/this-is-an-article/ is http://www.sitename.com.

To target browsers without support for location.origin use the following concise polyfill:

if (typeof location.origin === 'undefined')
    location.origin = location.protocol + '//' + location.host;

IIS Request Timeout on long ASP.NET operation

If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.

For example:

// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;

This value can also be configured in your web.config file in the httpRuntime configuration element:

<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300" 
  ... other configuration attributes ...
/>

enter image description here

Please note according to the MSDN documentation:

"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."

If you've already done this but are finding that your session is expiring then increase the ASP.NET HttpSessionState.Timeout value:

For example:

// Increase session timeout to thirty minutes
Session.Timeout = 30;

This value can also be configured in your web.config file in the sessionState configuration element:

<configuration>
  <system.web>
    <sessionState 
      mode="InProc"
      cookieless="true"
      timeout="30" />
  </system.web>
</configuration>

If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.

The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.

Python list of dictionaries search

You can use a generator expression:

>>> dicts = [
...     { "name": "Tom", "age": 10 },
...     { "name": "Mark", "age": 5 },
...     { "name": "Pam", "age": 7 },
...     { "name": "Dick", "age": 12 }
... ]

>>> next(item for item in dicts if item["name"] == "Pam")
{'age': 7, 'name': 'Pam'}

If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:

next((item for item in dicts if item["name"] == "Pam"), None)

And to find the index of the item, rather than the item itself, you can enumerate() the list:

next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)

Python TypeError must be str not int

you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

print("the furnace is now",temperature , "degrees!")

Directory.GetFiles: how to get only filename, not full path?

You can use System.IO.Path.GetFileName to do this.

E.g.,

string[] files = Directory.GetFiles(dir);
foreach(string file in files)
    Console.WriteLine(Path.GetFileName(file));

While you could use FileInfo, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles unless you need the additional functionality of the FileInfo class.

How to access component methods from “outside” in ReactJS?

As of React 16.3 React.createRef can be used, (use ref.current to access)

var ref = React.createRef()

var parent = (
  <div>
    <Child ref={ref} />
    <button onClick={e=>console.log(ref.current)}
  </div>
);

React.renderComponent(parent, document.body)

With ng-bind-html-unsafe removed, how do I inject HTML?

Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.

Example from the AngularJS documentation on $sce:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:

SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

Get the number of rows in a HTML table

Try:

var count = $('#gvPerformanceResult tr').length;

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I had this problem on a client's pc in IE 11 with Java installed. It worked fine in Chrome, but wouldn't work in IE. After several days of TS, I just tried unchecking ActiveX Filtering in settings->safety. Now Java works fine.

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

Automate scp file transfer using a shell script

The command scp can be used like a traditional UNIX cp. SO if you do :

scp -r myDirectory/ mylogin@host:TargetDirectory

will work

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

How to sum up elements of a C++ vector?

One more option which I did not notice in the answers is using std::reduce which is introduced in c++17.

But you may notice many compilers not supporting it (Above GCC 10 may be good). But eventually the support will come.

With std::reduce, the advantage comes when using the execution policies. Specifying execution policy is optional. When the execution policy specified is std::execution::par, the algorithm may use hardware parallel processing capabilities. The gain may be more clear when using big size vectors.

Example:

//SAMPLE
std::vector<int> vec = {2,4,6,8,10,12,14,16,18};
    
//WITHOUT EXECUTION POLICY
int sum = std::reduce(vec.begin(),vec.end());
    
//TAKING THE ADVANTAGE OF EXECUTION POLICIES
int sum2 = std::reduce(std::execution::par,vec.begin(),vec.end());
    
std::cout << "Without execution policy  " << sum << std::endl;
std::cout << "With execution policy  " << sum2 << std::endl;

You need <numeric> header for std::reduce. And '<execution>' for execution policies.

How do you make Git work with IntelliJ?

Literally, just restarted IntelliJ after it kept showing this "install git" message after I have pressed and installed git, and it disappeared, and git works

Command to get nth line of STDOUT

Try this sed version:

ls -l | sed '2 ! d'

It says "delete all the lines that aren't the second one".

Why do I always get the same sequence of random numbers with rand()?

None of you guys are answering his question.

with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?

From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Non-alphanumeric list order from os.listdir()

I think the order has to do with the way the files are indexed on your FileSystem. If you really want to make it adhere to some order you can always sort the list after getting the files.

How to render a PDF file in Android

you can use a simple method by import

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

and the XML code is

<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.github.barteksc.pdfviewer.PDFView>

and just declare and add a file to an asset folder and just assign the name

   PDFView  pdfView=findViewById(R.id.pdfv);       
    pdfView.fromAsset("agl.pdf").load();

ReactJS map through Object

Use Object.entries() function.

Object.entries(object) return:

[
    [key, value],
    [key, value],
    ...
]

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

{Object.entries(subjects).map(([key, subject], i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subject.name}</span>
    </li>
))}

How to load external scripts dynamically in Angular?

This might work. This Code dynamically appends the <script> tag to the head of the html file on button clicked.

const url = 'http://iknow.com/this/does/not/work/either/file.js';

export class MyAppComponent {
    loadAPI: Promise<any>;

    public buttonClicked() {
        this.loadAPI = new Promise((resolve) => {
            console.log('resolving promise...');
            this.loadScript();
        });
    }

    public loadScript() {
        console.log('preparing to load...')
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        node.async = true;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
    }
}

How come I can't remove the blue textarea border in Twitter Bootstrap?

Bootstrap 3

If you just want to change the color, change the variable (recommended):

Less or Customizer

@input-border-focus: red;

variables.less

Sass

$input-border-focus: red;

variables.sass

If you wan't to remove it completely, you'll have to overwrite the Mixin that sets the outline.

.form-control-focus(@color: @input-border-focus) {}

CSS

If you are using css overwrite it via:

.form-control:focus{
    border-color: #cccccc;
    -webkit-box-shadow: none;
    box-shadow: none;
}

Link to implementation

Java - creating a new thread

run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php

Converting of Uri to String

Uri is serializable, so you can save strings and convert it back when loading

when saving

String str = myUri.toString();

and when loading

Uri myUri = Uri.parse(str);

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

Command to delete all pods in all kubernetes namespaces

kubectl delete daemonsets,replicasets,services,deployments,pods,rc --all

to get rid of them pesky replication controllers too.

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

In my case, I use VS 2010, Oracle v11 64 bits. I might to publish in 64 bit mode (Setting to "Any Cpu" mode in Web Project configuration) and I might set IIS on Production Server to 32 Bit compability to false (because the the server is 64 bit and I like to take advantage it).

Then to solve the problem "Could not load file or assembly 'Oracle.DataAccess'":

  • In the Local PC and Server is installed Oracle v11, 64 Bit.
  • In all Local Dev PC I reference to Oracle.DataAccess.dll (C:\app\user\product\11.2.0\client_1\odp.net\bin\4) which is 64 bit.
  • In IIS Production Server, I set 32 bit compatibility to False.
  • The reference in the web project at System.Web.Mvc.dll was the version v3.0.0.1 in the local PC, however in Production is only instaled MVC version 3.0.0.0. So, the fix was locallly work with MVC 3.0.0.0 and not 3.0.0.1 and publish again on server, and it works.

Detect if device is iOS

UPDATE: My original answer doesn't cover iPad in desktop mode (the default changes to desktop mode in upcoming iPadOS 13 and higher).
That's fine for my usecases, if it's not for you, use this update:

// iPhone and iPad including iPadOS 13+ regardless of desktop mode settings

iOSiPadOS = /^iP/.test(navigator.platform) ||
           /^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4;
  • This should be safe as long as
    • desktop Macs don't support touch events at all
    • or not more than 4 touch points (current iOS devices support 5 touch points)
  • It's fast because the regexp ^ first checks the starting position of the platform string and stops if there is no "iP" (faster than searching the long UA string until the end anyway)
  • It's safer than navigator.userAgent check as navigator.platform is much less likely faked
  • Detects iPhone / iPad Simulator

ORIGINAL ANSWER:
Wow, a lot of longish tricky code here. Keep it simple, please!

This one is IMHO fast, save, and working well:

 iOS = /^iP/.test(navigator.platform);

  // or, if you prefer it verbose:
 iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);

How to convert a List<String> into a comma separated string without iterating List explicitly

import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

or you can use StringUtils:

   public static String join(Object[] array,
                              char separator)

   public static String join(Iterable<?> iterator,
                              char separator)

Joins the elements of the provided array/iterable into a single String containing the provided list of elements.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

Bouncy Castle still requires jars installed as far as I can tell.

I did a little test and it seemed to confirm this:

http://www.bouncycastle.org/wiki/display/JA1/Frequently+Asked+Questions

How can I get the current time in C#?

DateTime.Now is what you're searching for...

When should we use mutex and when should we use semaphore

It is very important to understand that a mutex is not a semaphore with count 1!

This is the reason there are things like binary semaphores (which are really semaphores with count 1).

The difference between a Mutex and a Binary-Semaphore is the principle of ownership:

A mutex is acquired by a task and therefore must also be released by the same task. This makes it possible to fix several problems with binary semaphores (Accidential release, recursive deadlock and priority inversion).

Caveat: I wrote "makes it possible", if and how these problems are fixed is up to the OS implementation.

Because the mutex is has to be released by the same task it is not very good for synchronization of tasks. But if combined with condition variables you get very powerful building blocks for building all kinds of ipc primitives.

So my recommendation is: if you got cleanly implemented mutexes and condition variables (like with POSIX pthreads) use these.

Use semaphores only if they fit exactly to the problem you are trying to solve, don't try to build other primitives (e.g. rw-locks out of semaphores, use mutexes and condition variables for these)

There is a lot of misunderstanding mutexes and semaphores. The best explanation I found so far is in this 3-Part article:

Mutex vs. Semaphores – Part 1: Semaphores

Mutex vs. Semaphores – Part 2: The Mutex

Mutex vs. Semaphores – Part 3 (final part): Mutual Exclusion Problems

How to pass multiple values through command argument in Asp.net?

I checked your code and seems to be no problem at all. please make sure Image commandArgument getting value. check it first binding in label whether you are getting value.

However, here is sample which I'm using in my project

<asp:GridView ID="GridViewUserScraps" ItemStyle-VerticalAlign="Top" AutoGenerateColumns="False" Width="100%" runat="server" OnRowCommand="GridViews_RowCommand" >
        <Columns>
            <asp:TemplateField SortExpression="SendDate">
                <ItemTemplate>
                <asp:Button ID="btnPost" CssClass="submitButton" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>' />

                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

first bind the GridView.

public void GetData()
{
   //bind ur GridView
   GridViewUserScraps.DataSource = dt;
   GridViewUserScraps.DataBind();
}

protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Comment")
    {
        string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
        string scrapid = commandArgs[0];
        string uid = commandArgs[1];
    }
}

Set a DateTime database field to "Now"

Use GETDATE()

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

UPDATE table SET date = GETDATE()

How to iterate over a JavaScript object?

->if we iterate over a JavaScript object using and find key of array of objects

Object.keys(Array).forEach(key => {

 console.log('key',key)

})

How to select only the records with the highest date in LINQ

Here is a simple way to do it

var lastPlayerControlCommand = this.ObjectContext.PlayerControlCommands
                                .Where(c => c.PlayerID == player.ID)
                                .OrderByDescending(t=>t.CreationTime)
                                .FirstOrDefault();

Also have a look this great LINQ place - LINQ to SQL Samples

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

I was using

<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version>
<executions>
    <execution>
        <id>runSomeAntTasks</id>
        <phase>test-compile</phase>
        .
        .
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</executions>

and changed it to

<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
    <id>runSomeAntTasks</id>
    <phase>integration-test</phase>
        .
        .

        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</executions>

and the error went away. Maybe it's not recommended to bind an execution to the test-compile phase so finding a different phase might be an alternate solution to adding plugin-management configuration to the maven lifecycle.

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

How to add a TextView to a LinearLayout dynamically in Android?

layout:

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

  <LinearLayout
      android:id="@+id/layoutTest"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      >
  </LinearLayout>
</RelativeLayout>

class file:

setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());

textView.setText("testDynamic textView");
layoutTest.addView(textView);

How do I remove newlines from a text file?

perl -p -i -e 's/\R//g;' filename

Must do the job.

Can I scroll a ScrollView programmatically in Android?

Yes, you can.

Let's say you got one Layout and inside that, you got many Views. So if you want to scroll to any View programmatically, you have to write the following code snippet:

For example:

content_main.xml

<ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</ScrollView>

MainActivity.java

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
Button btn = (Button) findViewById(R.id.ivEventBanner);
TextView txtView = (TextView) findViewById(R.id.ivEditBannerImage);

If you want to scroll to a specific View, let's say txtview, in this case, just write:

scrollView.smoothScrollTo(txtView.getScrollX(),txtView.getScrollY());

And you are done.

What are the options for (keyup) in Angular2?

I was searching for a way to bind to multiple key events - specifically, Shift+Enter - but couldn't find any good resources online. But after logging the keydown binding

<textarea (keydown)=onKeydownEvent($event)></textarea>

I discovered that the keyboard event provided all of the information I needed to detect Shift+Enter. Turns out that $event returns a fairly detailed KeyboardEvent.

onKeydownEvent(event: KeyboardEvent): void {
   if (event.keyCode === 13 && event.shiftKey) {
       // On 'Shift+Enter' do this...
   }
}

There also flags for the CtrlKey, AltKey, and MetaKey (i.e. Command key on Mac).

No need for the KeyEventsPlugin, JQuery, or a pure JS binding.

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

I had a similar issue. I resolved it by changing

<basicHttpBinding>

to

<basicHttpsBinding>

and also changed my URL to use https:// instead of http://.

Also in <endpoint> node, change

binding="basicHttpBinding" 

to

binding="basicHttpsBinding"

This worked.

When should I use File.separator and when File.pathSeparator?

You use separator when you are building a file path. So in unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + "var"+ File.separator + "temp"

You use the pathSeparator when you are dealing with a list of files like in a classpath. For example, if your app took a list of jars as argument the standard way to format that list on unix is: /path/to/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

So given a list of files you would do something like this:

String listOfFiles = ...
String[] filePaths = listOfFiles.split(File.pathSeparator);

How to import a jar in Eclipse

Just a comment on importing jars into Eclipse (plug-in development) projects:

In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages.

(BTW: Eclipse plug-ins are the same thing as OSGi bundles.)

There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

How to use SortedMap interface in Java?

TreeMap sorts by the key natural ordering. The keys should implement Comparable or be compatible with a Comparator (if you passed one instance to constructor). In you case, Float already implements Comparable so you don't have to do anything special.

You can call keySet to retrieve all the keys in ascending order.

Check if a string is a valid Windows directory (folder) path

    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;

        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

Regular expression for number with length of 4, 5 or 6

If the language you use accepts {}, you can use [0-9]{4,6}.

If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?.

How to have css3 animation to loop forever

I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.

Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div is restored, forcing the animations to restart.

All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head> section of your page:

<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>

BTW, the closing </head> in your code is misplaced: it must be before the starting <body>.

Simple regular expression for a decimal with a precision of 2

To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

-?(0|([1-9]\d*))(\.\d+)?

How to mount the android img file under linux?

I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img files all the time.

Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount

"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...

So, how to get the file from the inside of userdata.img?" To load .img files you have to select loop and load the .img Select loop

Next you select mount Select mount

Furius ISO mount handles all the other options loading the .img file to your /home/dir.

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

sendmail: how to configure sendmail on ubuntu?

Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.

#Change to your mail config directory:
cd /etc/mail

#Make a auth subdirectory
mkdir auth
chmod 700 auth  #maybe not, because I cannot apply cmd "cd auth" if I do so.

#Create a file with your auth information to the smtp server
cd auth
touch client-info

#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"

#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..

#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

#run 
sudo sendmailconfig

Copy/duplicate database without using mysqldump

You can duplicate a table without data by running:

CREATE TABLE x LIKE y;

(See the MySQL CREATE TABLE Docs)

You could write a script that takes the output from SHOW TABLES from one database and copies the schema to another. You should be able to reference schema+table names like:

CREATE TABLE x LIKE other_db.y;

As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:

INSERT INTO x SELECT * FROM other_db.y;

If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with per table table spaces.

If you do end up doing an INSERT INTO SELECT, be sure to temporarily turn off indexes with ALTER TABLE x DISABLE KEYS!

EDIT Maatkit also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.

Java: Converting String to and from ByteBuffer and associated problems

Unless things have changed, you're better off with

public static ByteBuffer str_to_bb(String msg, Charset charset){
    return ByteBuffer.wrap(msg.getBytes(charset));
}

public static String bb_to_str(ByteBuffer buffer, Charset charset){
    byte[] bytes;
    if(buffer.hasArray()) {
        bytes = buffer.array();
    } else {
        bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
    }
    return new String(bytes, charset);
}

Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I ran into a similar problem with the same error message using following code:

@Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())

I found a good answer here

Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

Be sure to import the following lib into your model:

using System.ComponentModel.DataAnnotations;

How to create multiple page app using react

(Make sure to install react-router using npm!)

To use react-router, you do the following:

  1. Create a file with routes defined using Route, IndexRoute components

  2. Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)

  3. Add {this.props.children} to make sure new pages will be rendered there
  4. Use the Link component to change pages

Step 1 routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

/**
 * Import all page components here
 */
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';

/**
 * All routes go here.
 * Don't forget to import the components above after adding new route.
 */
export default (
  <Route path="/" component={App}>
    <IndexRoute component={MainPage} />
    <Route path="/some/where" component={SomePage} />
    <Route path="/some/otherpage" component={SomeOtherPage} />
  </Route>
);

Step 2 entry point (where you do your DOM injection)

// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={history} />,
  document.getElementById('your-app')
);

Step 3 The App component (props.children)

In the render for your App component, add {this.props.children}:

render() {
  return (
    <div>
      <header>
        This is my website!
      </header>

      <main>
        {this.props.children}
      </main>

      <footer>
        Your copyright message
      </footer>
    </div>
  );
}

Step 4 Use Link for navigation

Anywhere in your component render function's return JSX value, use the Link component:

import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

You can easily install it by writing

Install-Package AjaxControlToolkit in package manager console.

for more information you can check this link

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

Switch statement with returns -- code correctness

What do you think? Is it fine to remove them? Or would you keep them for increased "correctness"?

It is fine to remove them. Using return is exactly the scenario where break should not be used.

Error parsing yaml file: mapping values are not allowed here

Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:

Wrong

- path: / 
    backend: 
      serviceName: <service_name> 
      servicePort: <port> 

Correct

- path: /
  backend:
    serviceName: <service_name>
    servicePort: <port>

Converting json results to a date

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

Android fastboot waiting for devices

To use the fastboot command you first need to put your device in fastboot mode:

$ adb reboot bootloader

Once the device is in fastboot mode, you can boot it with your own kernel, for example:

$ fastboot boot myboot.img

The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:

$ fastboot flash boot myboot.img

Hope that helps.

Change the Right Margin of a View Programmatically?

EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
    }
}

You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);

I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

NOTE

Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

This answer may be late reply but it will be useful for seeing this topic in future.

The features of .NET framework 4.5 can be seen in the following link.

To summarize:

  • Installation

    .NET Framework 4.5 does not support Windows XP or Windows Server 2003, and therefore, if you have to create applications that target these operating systems, you will need to stay with .NET Framework 4.0. In contrast, Windows 8 and Windows Server 2012 in all of their editions include .NET Framework 4.5.

  • Support for Arrays Larger than 2 GB on 64-bit Platforms
  • Enhanced Background Server Garbage Collection
  • Support for Timeouts in Regular Expression Evaluations
  • Support for Unicode 6.0.0 in Culture-Sensitive Sorting and Casing Rules on Windows 8
  • Simple Default Culture Definition for an Application Domain
  • Internationalized Domain Names in Windows 8 Apps

MVC 4 Edit modal form using Bootstrap

In reply to Dimitrys answer but using Ajax.BeginForm the following works at least with MVC >5 (4 not tested).

  1. write a model as shown in the other answers,

  2. In the "parent view" you will probably use a table to show the data. Model should be an ienumerable. I assume, the model has an id-property. Howeverm below the template, a placeholder for the modal and corresponding javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="[email protected]"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    

note the "editor-success-id" in data table rows.

  1. The dataRowView is a partial containing the presentation of an model's item.

    @model ModelView
    @{
        var item = Model;
    }
    <div class="row">
            // some data 
            <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
    </div>
    
  2. Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ... ).

    @model Model
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="editor-title">Title</h4>
    </div>
    @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "editor-success-" + @Model.Id,
                            OnSuccess = "success",
                            OnFailure = "failure",
                        }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)
        <div class="modal-body">
            <div class="form-horizontal">
                // Models input fields
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }
    

This is where magic happens: in AjaxOptions, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.

This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.

But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:

  1. the corresponding controller action method for the partial edit modal

    [HttpGet]
    public async Task<ActionResult> EditPartData(Guid? id)
    {
        // Find the data row and return the edit form
        Model input = await db.Models.FindAsync(id);
        return PartialView("EditModel", input);
    }
    
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> MyEditAction([Bind(Include =
       "Id,Fields,...")] ModelView input)
    {
        if (TryValidateModel(input))
        {  
            // save changes, return new data row  
            // status code is something in 200-range
            db.Entry(input).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return PartialView("dataRowView", (ModelView)input);
        }
    
        // set the "error status code" that will redisplay the modal
        Response.StatusCode = 400;
        // and return the edit form, that will be displayed as a 
        // modal again - including the modelstate errors!
        return PartialView("EditModel", (Model)input);
    }
    

This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.

Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js (may be installed by NuGet):

        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));

Determine the type of an object?

On instances of object you also have the:

__class__

attribute. Here is a sample taken from Python 3.3 console

>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
...     pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>

Beware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the isinstance built in function.

How to create a new branch from a tag?

Wow, that was easier than I thought:

git checkout -b newbranch v1.0

Auto insert date and time in form input field?

<input type="date" id="myDate"  />

<script type="text/javascript">
function SetDate()
{
var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;


document.getElementById('myDate').value = today;
}
</script>

<body onload="SetDate();">

found here: http://jsbin.com/oqekar/1/edit?html,js,output

POST request with JSON body

I made API sending data via form on website to prosperworks based on @Rocket Hazmat, @dbau and @maraca code. I hope, it will help somebody:

<?php

if(isset($_POST['submit'])) {
    //form's fields name:
    $name = $_POST['nameField'];
    $email = $_POST['emailField'];

    //API url:
    $url = 'https://api.prosperworks.com/developer_api/v1/leads';

    //JSON data(not exact, but will be compiled to JSON) file:
    //add as many data as you need (according to prosperworks doc):
    $data = array(
                            'name' => $name,
                            'email' => array('email' => $email)
                        );

    //sending request (according to prosperworks documentation):
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n".
             "X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
             "X-PW-Application:developer_api\r\n".
             "X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
            'method'  => 'POST',
            'content' => json_encode($data)
        )
    );

    //engine:
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    //compiling to JSON (as wrote above):
    $resultData = json_decode($result, TRUE);
    //display what was sent:
    echo '<h2>Sent: </h2>';
    echo $resultData['published'];
    //dump var:
    var_dump($result);

}
?>
<html>
    <head>
    </head>

    <body>

        <form action="" method="POST">
            <h1><?php echo $msg; ?></h1>
            Name: <input type="text" name="nameField"/>
            <br>
            Email: <input type="text" name="emailField"/>
            <input type="submit" name="submit" value="Send"/>
        </form>

    </body>
</html>

How do I use Assert to verify that an exception has been thrown?

Usually your testing framework will have an answer for this. But if it's not flexible enough, you can always do this:

try {
    somethingThatShouldThrowAnException();
    Assert.Fail(); // If it gets to this line, no exception was thrown
} catch (GoodException) { }

As @Jonas points out, this DOES NOT work for catching a base Exception:

try {
    somethingThatShouldThrowAnException();
    Assert.Fail(); // raises AssertionException
} catch (Exception) {
    // Catches the assertion exception, and the test passes
}

If you absolutely must catch Exception, you need to rethrow the Assert.Fail(). But really, this is a sign you shouldn't be hand-writing this; check your test framework for options, or see if you can throw a more meaningful exception to test for.

catch (AssertionException) { throw; }

You should be able to adapt this approach to whatever you like -- including specifying what kinds of exceptions to catch. If you only expect certain types, finish the catch blocks off with:

} catch (GoodException) {
} catch (Exception) {
    // not the right kind of exception
    Assert.Fail();
}

What does "#include <iostream>" do?

In order to read or write to the standard input/output streams you need to include it.

int main( int argc, char * argv[] )
{
    std::cout << "Hello World!" << std::endl;
    return 0;
}

That program will not compile unless you add #include <iostream>

The second line isn't necessary

using namespace std;

What that does is tell the compiler that symbol names defined in the std namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example

#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

Notice you no longer need to refer to the output stream with the fully qualified name std::cout and can use the shorter name cout.

I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:

#include <iostream>
using std::cout;
using std::endl;

int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

But that is a matter of personal preference.

Eclipse error ... cannot be resolved to a type

  • Right click Project > Properties
  • Java Build Path > Add Class Folder
  • Select the bin folder
  • Click ok
  • Switch Order and Export tab
  • Select the newly added bin path move UP
  • Click Apply button

enter image description here

When do you use varargs in Java?

Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

String.format("This is an integer: %d", myInt);
String.format("This is an integer: %d and a string: %s", myInt, myString);

What is the difference between float and double?

The built-in comparison operations differ as in when you compare 2 numbers with floating point, the difference in data type (i.e. float or double) may result in different outcomes.

How to pass multiple parameters in thread in VB

Well, the straightforward method is to create an appropriate class/structure which holds all your parameter values and pass that to the thread.

Another solution in VB10 is to use the fact that lambdas create a closure, which basically means the compiler doing the above automatically for you:

Dim evaluator As New Thread(Sub()
                                testthread(goodList, 1)
                            End Sub)

mysqli_real_connect(): (HY000/2002): No such file or directory

This worked for me.

Locate config.sample.inc.php

Change

$cfg['Servers'][$i]['host'] = 'localhost';

into

$cfg['Servers'][$i]['host'] = '127.0.0.1';

Save.

Then rename the file and remove sample from the name.

How to split a dataframe string column into two columns?

If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:

df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]  

Where is adb.exe in windows 10 located?

You'll find it in the AppData folder if you choose to install it in the default location. Otherwise, it will be located at the folder where you installed your Android SDK/platform-tools folder.

Set today's date as default date in jQuery UI datepicker

I tried many ways and came up with my own solution which works absolutely as required.

"mydate" is the ID of input or datepicker element/control.

        $(document).ready(function () {

        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);

        onlyDate = today.getDate();

        if (onlyDate.toString().length == 2) {
            dateNewFormat += '-' + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }
        $('#mydate').val(dateNewFormat);
    });

find without recursion

I believe you are looking for -maxdepth 1.

How to declare a variable in a PostgreSQL query

I want to propose an improvement to @DarioBarrionuevo's answer, to make it simpler leveraging temporary tables.

DO $$
    DECLARE myvar integer = 5;
BEGIN
    CREATE TEMP TABLE tmp_table ON COMMIT DROP AS
        -- put here your query with variables:
        SELECT * 
        FROM yourtable
        WHERE id = myvar;
END $$;

SELECT * FROM tmp_table;

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

For iOS<10

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    //-- Set Notification
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) 
    {
           // iOS 8 Notifications
           [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];

           [application registerForRemoteNotifications];
    }
    else
    {
          // iOS < 8 Notifications
          [application registerForRemoteNotificationTypes:
                     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
    }

     //--- your custom code
     return YES;
}

For iOS10

https://stackoverflow.com/a/39383027/3560390

Android and setting width and height programmatically in dp units

Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:

final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);

And your dimens.xml will have:

<dimen name="dimen_entry_in_dp">72dp</dimen>

Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.

How to fix UITableView separator on iOS 7?

UITableView has a property separatorInset. You can use that to set the insets of the table view separators to zero to let them span the full width of the screen.

[tableView setSeparatorInset:UIEdgeInsetsZero];

Note: If your app is also targeting other iOS versions, you should check for the availability of this property before calling it by doing something like this:

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Connection refused to MongoDB errno 111

One other option is to just repair your database like so (note: db0 directory should be pre-created first):

mongod --dbpath /var/lib/mongodb/ --repairpath /var/lib/mongodb/db0

This is also an acceptable option in production environments...

Javascript Append Child AFTER Element

This suffices :

 parentGuest.parentNode.insertBefore(childGuest, parentGuest.nextSibling || null);

since if the refnode (second parameter) is null, a regular appendChild is performed. see here : http://reference.sitepoint.com/javascript/Node/insertBefore

Actually I doubt that the || null is required, try it and see.

Git: Recover deleted (remote) branch

If your organization uses JIRA or another similar system that is tied into git, you can find the commits listed on the ticket itself and click the links to the code changes. Github deletes the branch but still has the commits available for cherry-picking.

Angular 2 @ViewChild annotation returns undefined

I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit; you need to wait for the view to be initialized before you can access your @ViewChild. However, my @ViewChild was still returning null. The problem was my *ngIf. The *ngIf directive was killing my controls component so I couldn't reference it.

import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './controls/controls.component';
import {SlideshowComponent} from './slideshow/slideshow.component';

@Component({
    selector: 'app',
    template:  `
        <controls *ngIf="controlsOn"></controls>
        <slideshow (mousemove)="onMouseMove()"></slideshow>
    `,
    directives: [SlideshowComponent, ControlsComponent]
})

export class AppComponent {
    @ViewChild(ControlsComponent) controls:ControlsComponent;

    controlsOn:boolean = false;

    ngOnInit() {
        console.log('on init', this.controls);
        // this returns undefined
    }

    ngAfterViewInit() {
        console.log('on after view init', this.controls);
        // this returns null
    }

    onMouseMove(event) {
         this.controls.show();
         // throws an error because controls is null
    }
}

Hope that helps.

EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren instead of @ViewChild.

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

Dictionary returning a default value if the key does not exist

I created a DefaultableDictionary to do exactly what you are asking for!

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace DefaultableDictionary {
    public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
        private readonly IDictionary<TKey, TValue> dictionary;
        private readonly TValue defaultValue;

        public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
            this.dictionary = dictionary;
            this.defaultValue = defaultValue;
        }

        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
            return dictionary.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return GetEnumerator();
        }

        public void Add(KeyValuePair<TKey, TValue> item) {
            dictionary.Add(item);
        }

        public void Clear() {
            dictionary.Clear();
        }

        public bool Contains(KeyValuePair<TKey, TValue> item) {
            return dictionary.Contains(item);
        }

        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
            dictionary.CopyTo(array, arrayIndex);
        }

        public bool Remove(KeyValuePair<TKey, TValue> item) {
            return dictionary.Remove(item);
        }

        public int Count {
            get { return dictionary.Count; }
        }

        public bool IsReadOnly {
            get { return dictionary.IsReadOnly; }
        }

        public bool ContainsKey(TKey key) {
            return dictionary.ContainsKey(key);
        }

        public void Add(TKey key, TValue value) {
            dictionary.Add(key, value);
        }

        public bool Remove(TKey key) {
            return dictionary.Remove(key);
        }

        public bool TryGetValue(TKey key, out TValue value) {
            if (!dictionary.TryGetValue(key, out value)) {
                value = defaultValue;
            }

            return true;
        }

        public TValue this[TKey key] {
            get
            {
                try
                {
                    return dictionary[key];
                } catch (KeyNotFoundException) {
                    return defaultValue;
                }
            }

            set { dictionary[key] = value; }
        }

        public ICollection<TKey> Keys {
            get { return dictionary.Keys; }
        }

        public ICollection<TValue> Values {
            get
            {
                var values = new List<TValue>(dictionary.Values) {
                    defaultValue
                };
                return values;
            }
        }
    }

    public static class DefaultableDictionaryExtensions {
        public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
            return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
        }
    }
}

This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.

The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.

Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);

Blog post on the usage as well.

ExecuteNonQuery doesn't return results

Could you post the exact query? The ExecuteNonQuery method returns the @@ROWCOUNT Sql Server variable what ever it is after the last query has executed is what the ExecuteNonQuery method returns.

using favicon with css

You can't set a favicon from CSS - if you want to do this explicitly you have to do it in the markup as you described.

Most browsers will, however, look for a favicon.ico file on the root of the web site - so if you access http://example.com most browsers will look for http://example.com/favicon.ico automatically.

SpringMVC RequestMapping for GET parameters

Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:

@RequestMapping("/userGrid", 
params = {"_search", "nd", "rows", "page", "sidx", "sort"})
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "_search") String search, 
@RequestParam(value = "nd") int nd, 
@RequestParam(value = "rows") int rows, 
@RequestParam(value = "page") int page, 
@RequestParam(value = "sidx") int sidx, 
@RequestParam(value = "sort") Sort sort) {
// Stuff here
}

This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.

Angular ng-if="" with multiple arguments

Just to clarify, be aware bracket placement is important!

These can be added to any HTML tags... span, div, table, p, tr, td etc.

AngularJS

ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

Angular2+

*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets

It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.

boolean check1 = Your conditional check here...
...

Getting the object's property name

you can easily iterate in objects

eg: if the object is var a = {a:'apple', b:'ball', c:'cat', d:'doll', e:'elephant'};

Object.keys(a).forEach(key => {
   console.log(key) // returns the keys in an object
   console.log(a[key])  // returns the appropriate value 
})

How do I replace text inside a div element?

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById(field_name);

  fieldNameElement.removeChild(fieldNameElement.firstChild);
  var newText = document.createTextNode("New Text");
  fieldNameElement.appendChild(newText);
}

Hiding a form and showing another when a button is clicked in a Windows Forms application

i believe the following code will only run after form1 is closed

 while (true)
    {
        if (form1.Visible == false)
            form2.Show();
    }

Why not start your form2 from form1 instead?

Form2 form2 = new Form2();
 private void button1_Click_1(object sender, EventArgs e)
    {
        if (richTextBox1.Text != null)
        {
            form1.Visible=false;
            form2.Show();

        }
        else MessageBox.Show("Insert Attributes First !");

    }

Plotting of 1-dimensional Gaussian distribution function

The correct form, based on the original syntax, and correctly normalized is:

def gaussian(x, mu, sig):
    return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)

How to open a new tab in GNOME Terminal from command line?

Just in case, you want to open

  • a new window
  • with two tabs
  • and executing command in there
  • and having them stay open...

here you go:

gnome-terminal --geometry=73x16+0+0 --window \
  --working-directory=/depot --title='A' --command="bash -c ls;bash" \
  --tab --working-directory=/depot/kn --title='B' --command="bash -c ls;bash"

(same for mate-terminal btw.)

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

How to cast Object to its actual type?

I don't think you can (not without reflection), you should provide a type to your function as well:

void MyMethod(Object obj, Type t)
{
    var convertedObject = Convert.ChangeType(obj, t);
    ...
}

UPD:

This may work for you:

void MyMethod(Object obj)
{
    if (obj is A)
    {
        A a = obj as A;
        ...
    } 
    else if (obj is B)
    {
        B b = obj as B;
        ...
    }
}

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

PHP json_decode() returns NULL with valid JSON?

Here is here I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode() to return null

Remove a cookie

I had the same problem in my code and found that it was a cookie path issue. Check out this stack overflow post: Can't delete php set cookie

I had set the cookie using a path value of "/", but didn't have any path value when I tried to clear it, so it didn't clear. So here is an example of what worked:

Setting the cookie:

$cookiePath = "/";
$cookieExpire = time()+(60*60*24);//one day -> seconds*minutes*hours
setcookie("CookieName",$cookieValue,$cookieExpire,$cookiePath);

Clearing the cookie:

setcookie("cookieName","", time()-3600, $cookiePath);
unset ($_COOKIE['cookieName']);

Hope that helps.

How to install grunt and how to build script with it

You should be installing grunt-cli to the devDependencies of the project and then running it via a script in your package.json. This way other developers that work on the project will all be using the same version of grunt and don't also have to install globally as part of the setup.

Install grunt-cli with npm i -D grunt-cli instead of installing it globally with -g.

//package.json

...

"scripts": {
  "build": "grunt"
}

Then use npm run build to fire off grunt.

Center text in div?

For the parent div,use following CSS:

style="display: flex;align-items: center;"

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

How to install Visual C++ Build tools?

I just stumbled onto this issue accessing some Python libraries: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". The latest link to that is actually here: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

When you begin the installer, it will have several "options" enabled which will balloon the install size to 5gb. If you have Windows 10, you'll need to leave selected the "Windows 10 SDK" option as mentioned here.

enter image description here

I hope it helps save others time!

How to draw in JPanel? (Swing/graphics Java)

Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}

database attached is read only

You need to go to the new folder properties > security tab, and give permissions to the SQL user that has rights on the DATA folder from the SQL server installation folder.

How Does Modulus Divison Work

It's simple, Modulus operator(%) returns remainder after integer division. Let's take the example of your question. How 27 % 16 = 11? When you simply divide 27 by 16 i.e (27/16) then you get remainder as 11, and that is why your answer is 11.

Eclipse will not open due to environment variables

Another alternative is to re-run the JRE setup. It typically installs a default JRE by placing java.exe, javaw.exe, etc. in your system folder. That would place the executables in your path, which should be sufficient, based on the note in the error message that it searched your path for javaw.exe

Best way to convert text files between character sets?

Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.

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

Here how you can print without using Data::Dumper

print "@{[%hash]}";

How to set default value for form field in Symfony2?

There is a very simple way, you can set defaults as here :

$defaults = array('sortby' => $sortby,'category' => $category,'page' => 1);

$form = $this->formfactory->createBuilder('form', $defaults)
->add('sortby','choice')
->add('category','choice')
->add('page','hidden')
->getForm();

How to draw a rectangle around a region of interest in python

You can use cv2.rectangle():

cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)

Draws a simple, thick, or filled up-right rectangle.

The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.

Parameters
    img   Image.
    pt1   Vertex of the rectangle.
    pt2    Vertex of the rectangle opposite to pt1 .
    color Rectangle color or brightness (grayscale image).
    thickness  Thickness of lines that make up the rectangle. Negative values,
    like CV_FILLED , mean that the function has to draw a filled rectangle.
    lineType  Type of the line. See the line description.
    shift   Number of fractional bits in the point coordinates.

I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:

# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
              color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

Working with huge files in VIM

This has been a recurring question for many years. (The numbers keep changing, but the concept is the same: how do I view or edit files that are larger than memory?)

Obviously more or less are good approaches to merely reading the files --- less even offers vi like keybindings for scrolling and searching.

A Freshmeat search on "large files" suggests that two editors would be particularly suited to your needs.

One would be: lfhex ... a large file hex editor (which depends on Qt). That one, obviously, entails using a GUI.

Another would seem to be suited to console use: hed ... and it claims to have a vim-like interface (including an ex mode?).

I'm sure I've seen other editors for Linux/UNIX that were able to page through files without loading their entirety into memory. However, I don't recall any of their names. I'm making this response a "wiki" entry to encourage others to add their links to such editors. (Yes, I am familiar with ways to work around the issue using split and cat; but I'm thinking of editors, especially console/curses editors which can dispense with that and save us the time/latencies and disk space overhead that such approaches entail).

Is div inside list allowed?

As an addendum: Before HTML 5 while a div inside a li is valid, a div inside a dl, dd, or dt is not!

Key Listeners in python?

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

Disable vertical scroll bar on div overflow: auto

These two CSS properties can be used to hide the scrollbars:

overflow-y: hidden; // hide vertical
overflow-x: hidden; // hide horizontal

Python: Get relative path from comparing two absolute paths

os.path.relpath:

Return a relative filepath to path either from the current directory or from an optional start point.

>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'

So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

In Python3 you can use PurePath.relative_to:

Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path

>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')

>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')

>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'

How can I create database tables from XSD files?

The best way to create the SQL database schema using an XSD file is a program called Altova XMLSpy, this is very simple:

  1. Create a new project
  2. On the DTDs / Schemas folder right clicking and selecting add files
  3. Selects the XSD file
  4. Open the XSD file added by double-clicking
  5. Go to the toolbar and look Conversion
  6. They select Create structure database from XML schema
  7. Selects the data source
  8. And finally give it to export the route calls immediately leave their scrip schemas with SQL Server to execute the query.

Hope it helps.

Select data between a date/time range

You probably need to use STR_TO_DATE function:

select * from hockey_stats 
where
  game_date between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
                and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s') 
order by game_date desc;

(if game_date is a string, you might need to use STR_TO_DATE on it)

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

How to merge multiple lists into one list in python?

a = ['it']
b = ['was']
c = ['annoying']

a.extend(b)
a.extend(c)

# a now equals ['it', 'was', 'annoying']

SQL server stored procedure return a table

Though this question is very old but as a new in Software Development I can't stop my self to share what I have learnt :D

Creation of Stored Procedure:

CREAET PROC usp_ValidateUSer
(
    @UserName nVARCHAR(50),
    @Password nVARCHAR(50)
)
AS

BEGIN
    IF EXISTS(SELECT '#' FROM Users WHERE Username=@UserName AND Password=@Password)
    BEGIN
        SELECT u.UserId, u.Username, r.UserRole
        FROM Users u
        INNER JOIN UserRoles r
        ON u.UserRoleId=r.UserRoleId
    END
END

Execution of Stored Procedure:

(If you want to test the execution of Stored Procedure in SQL)

EXEC usp_ValidateUSer @UserName='admin', @Password='admin'

Th Output:

enter image description here

show all tags in git log

Note: the commit 5e1361c from brian m. carlson (bk2204) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:

log: properly handle decorations with chained tags

git log did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly because parse_object had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.

Call parse_object to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.

Example:

git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full

How to properly make a http web GET request

Another way is using 'HttpClient' like this:

using System;
using System.Net;
using System.Net.Http;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making API Call...");
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
                HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
                response.EnsureSuccessStatusCode();
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Result: " + result);
            }
            Console.ReadLine();
        }
    }
}

Check HttpClient vs HttpWebRequest from stackoverflow and this from other.

Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
   client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
   HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
   response.EnsureSuccessStatusCode();
   string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);           
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

what's data-reactid attribute in html?

Custom Data attribute in HTML5

Would like to quote Ian's comment in my answer:

It's just an attribute (a valid one) on the element that you can use to store data/info about it.

This code then retrieves it later in the event handler, and uses it to find the target output element. It effectively stores the class of the div where its text should be outputted.

reactid is just a suffix, you can have any name here eg: data-Ayman.

If you want to find the difference check the fiddles in this SO answer and comment.

Best way to find the intersection of multiple sets?

I believe the simplest thing to do is:

#assuming three sets
set1 = {1,2,3,4,5}
set2 = {2,3,8,9}
set3 = {2,10,11,12}

#intersection
set4 = set1 & set2 & set3

set4 will be the intersection of set1 , set2, set3 and will contain the value 2.

print(set4)

set([2])

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

javascript unexpected identifier

In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?

gnuplot plotting multiple line graphs

In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'

plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4 

note that the command above assumes that you have a file named ls.dat with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.