Programs & Examples On #Topaz signatures

Topaz electronic signature capture devices

Navigation bar show/hide

This code will help you.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] 
initWithTarget:self action:@selector(showHideNavbar:)];
[self.view addGestureRecognizer:tapGesture];

-(void) showHideNavbar:(id) sender 
{ 
// write code to show/hide nav bar here 
// check if the Navigation Bar is shown
if (self.navigationController.navigationBar.hidden == NO)
{
// hide the Navigation Bar
[self.navigationController setNavigationBarHidden:YES animated:YES];
}
// if Navigation Bar is already hidden
else if (self.navigationController.navigationBar.hidden == YES)
{
// Show the Navigation Bar
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}

PHP list of specific files in a directory

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
        {
            $thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
        }
    }
    closedir($handle);
}

A simple way to look at the extension using substr and strrpos

Accessing Redux state in an action creator?

I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.

In the reducer do something like:

const state = this.state;
const apple = this.state.apples;

If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.

Please correct me if I'm wrong!!!

Best way to format integer as string with leading zeros?

This is my Python function:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

Use Awk to extract substring

You just want to set the field separator as . using the -F option and print the first field:

$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0

Same thing but using cut:

$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0

Or with sed:

$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0

Even grep:

$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0

Python exit commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

Avoid Adding duplicate elements to a List C#

not a good way but kind of quick fix, take a bool to check if in whole list there is any duplicate entry.

bool containsKey;
string newKey;

public void addKey(string newKey)
{
    foreach (string key in MyKeys)
    {
        if (key == newKey)
        {
            containsKey = true;
        }
    }

    if (!containsKey)
    {
        MyKeys.add(newKey);
    }
    else
    {
        containsKey = false;
    }
}

Extract filename and extension in Bash

Maybe there is an option in tar to do this; did you check the man? Otherwise, you can use Bash string expansion:

test="mpc-1.0.1.tar.gz"
noExt="${test/.tar.gz/}" # Remove the string '.tar.gz'
echo $noExt

c++ array - expression must have a constant value

When you declare a variable as here

int a[10][10];

you are telling the C++ compiler that you want 100 consecutive integers allocated in the program's memory at runtime. The compiler will then provide for your program to have that much memory available and all is well with the world.

If however you tell the compiler

int x = 9001;
int y = 5;
int a[x][y];

the compiler has no way of knowing how much memory you are actually going to need at run time without doing a lot of very complex analysis to track down every last place where the values of x and y changed [if any]. Rather than support such variable size arrays, C++ and C strongly suggest if not outright demand that you use malloc() to manually allocate the space you want.

TL;DR

int x = 5;
int y = 5;
int **a = malloc(x*sizeof(int*));
for(int i = 0; i < y; i++) {
    a[i] = malloc(sizeof(int*)*y);
}

a is now a 2D array of size 5x5 and will behave the same as int a[5][5]. Because you have manually allocated memory, C++ and C demand that you delete it by hand too...

for(int i = 0; i < x; i++) {
    free(a[i]); // delete the 2nd dimension array
}
free(a); // delete a itself

IE6/IE7 css border on select element

Check out this code... hope ur happy :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<style type="text/css">
*{margin:0;padding:0;}
select {font: normal 13px Arial, SansSerif, Verdana; color: black;}
.wrapper{width:198px; position: relative;  height: 20px; overflow: hidden; border-top:1px solid #dddddd; border-left:1px solid #dddddd;}
.Select{color: black; background: #fff;position: absolute; width: 200px; top: -2px; left: -2px;}
optgroup{background-color:#0099CC;color:#ffffff;}
</style>
</head>

<body>
<div class="wrapper">
<select class="Select">
<optgroup label="WebDevelopment"></optgroup>
<option>ASP</option>
<option>PHP</option>
<option>ColdFusion</option>
<optgroup label="Web Design"></optgroup>
<option>Adobe Photoshop</option>
<option>DreamWeaver</option>
<option>CSS</option>
<option>Adobe Flash</option>
</select>
</div>
</body>
</html>

Sajay

How to wrap async function calls into a sync function in Node.js or Javascript?

I struggled with this at first with node.js and async.js is the best library I have found to help you deal with this. If you want to write synchronous code with node, approach is this way.

var async = require('async');

console.log('in main');

doABunchOfThings(function() {
  console.log('back in main');
});

function doABunchOfThings(fnCallback) {
  async.series([
    function(callback) {
      console.log('step 1');
      callback();
    },
    function(callback) {
      setTimeout(callback, 1000);
    },
    function(callback) {
      console.log('step 2');
      callback();
    },
    function(callback) {
      setTimeout(callback, 2000);
    },
    function(callback) {
      console.log('step 3');
      callback();
    },
  ], function(err, results) {
    console.log('done with things');
    fnCallback();
  });
}

this program will ALWAYS produce the following...

in main
step 1
step 2
step 3
done with things
back in main

Get file name from URI string in C#

this is my sample you can use:

        public static string GetFileNameValidChar(string fileName)
    {
        foreach (var item in System.IO.Path.GetInvalidFileNameChars())
        {
            fileName = fileName.Replace(item.ToString(), "");
        }
        return fileName;
    }

    public static string GetFileNameFromUrl(string url)
    {
        string fileName = "";
        if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
        {
            fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
        }
        string ext = "";
        if (!string.IsNullOrEmpty(fileName))
        {
            ext = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(ext))
                ext = ".html";
            else
                ext = "";
            return GetFileNameValidChar(fileName + ext);

        }

        fileName = Path.GetFileName(url);
        if (string.IsNullOrEmpty(fileName))
        {
            fileName = "noName";
        }
        ext = Path.GetExtension(fileName);
        if (string.IsNullOrEmpty(ext))
            ext = ".html";
        else
            ext = "";
        fileName = fileName + ext;
        if (!fileName.StartsWith("?"))
            fileName = fileName.Split('?').FirstOrDefault();
        fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
        return GetFileNameValidChar(fileName);
    }

Usage:

var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");

How to export query result to csv in Oracle SQL Developer?

To take an export to your local system from sql developer.

Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv

    SPOOL "Path where you want to save the file"
    SELECT /*csv*/ * FROM TABLE_NAME;

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Java Date cut off time information

Have you looked at Joda ? It's a much easier and more intuitive way to work with dates and times. For instance you can convert trivially between (say) LocalDateTime and LocalDate objects.

e.g. (to illustrate the API)

LocalDate date = new LocalDateTime(milliseconds).toLocalDate()

Additionally it solves some thread-safety issues with date/time formatters and is to be strongly recommended for working with any date/time issues in Java.

Detect enter press in JTextField

If you want to set a default button action in a JTextField enter, you have to do this:

//put this after initComponents();

textField.addActionListener(button.getActionListeners()[0]);

It is [0] because a button can has a lot of actions, but normally just has one (ActionPerformed).

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

With Java 8 and later, use the java.time package.

ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();

ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.

Allow all remote connections, MySQL

GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

Will allow a specific user to log on from anywhere.

It's bad because it removes some security control, i.e. if an account is compromised.

How to compare each item in a list with the rest, only once?

Use itertools.combinations(mylist, 2)

mylist = range(5)
for x,y in itertools.combinations(mylist, 2):
    print x,y

0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
2 4
3 4

Use jQuery to get the file input's selected filename without the path

We can also remove it using match

var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

How to make <div> fill <td> height

You could try making your div float:

.thatSetsABackgroundWithAnIcon{

    float:left;
}

Alternativelly, use inline-block:

.thatSetsABackgroundWithAnIcon{

    display:inline-block;
}

Working example of the inline-block method:

_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <div style="border:1px solid red; height:100%; display:inline-block;">_x000D_
        I want cell to be the full height_x000D_
      </div>_x000D_
    </td>_x000D_
    <td>_x000D_
      This cell_x000D_
      <br/>is higher_x000D_
      <br/>than the_x000D_
      <br/>first one_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to construct a std::string from a std::vector<char>?

I think you can just do

std::string s( MyVector.begin(), MyVector.end() );

where MyVector is your std::vector.

Python Prime number checker

This would do the job:

number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
    print "number is not prime"
else:
    a=2
    check = True
    while a != number:
        if number%a == 0:
            print "Number is not prime"
            check = False
            break
        a+=1
    if check == True:
        print "Number is prime" 

How to delete all the rows in a table using Eloquent?

I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate() resets. I also didn't want to use DB:: anything because I wanted to operate directly off of the model object. So, I went with this:

Model::whereNotNull('id')->delete();

Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id column exists and is never null. I don't know if this is the best choice, but it works for my purposes.

Drawing circles with System.Drawing

if you want to draw circle on button then this code might be use full. else if you want to draw a circle on other control just change the name of control and also event. like here event button is called. if you want to draw this circle in group box call the Groupbox event. regards

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.button1.Location = new Point(108, 12);
       // this.Paint += new PaintEventHandler(Form1_Paint);
        this.button1.Paint += new PaintEventHandler(button1_Paint);
    }
    void button1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = this.button1.CreateGraphics();
        Pen pen = new Pen(Color.Red);
        g.DrawEllipse(pen, 10, 10, 20, 20);

    }





}

Copy entire directory contents to another directory?

public static void copyFolder(File source, File destination)
{
    if (source.isDirectory())
    {
        if (!destination.exists())
        {
            destination.mkdirs();
        }

        String files[] = source.list();

        for (String file : files)
        {
            File srcFile = new File(source, file);
            File destFile = new File(destination, file);

            copyFolder(srcFile, destFile);
        }
    }
    else
    {
        InputStream in = null;
        OutputStream out = null;

        try
        {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, length);
            }
        }
        catch (Exception e)
        {
            try
            {
                in.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }

            try
            {
                out.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}

How do I determine the current operating system with Node.js

when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

use

    function isOSWin64() {
      return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
    }

(check here for details)

Invalid shorthand property initializer

In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:

    var rishabh = {
        class:"final year",
        roll:123,
        percent: function(marks1, marks2, marks3){
                      total = marks1 + marks2 + marks3;
                      this.percentage = total/3 }
                    };

john.percent(85,89,95);
console.log(rishabh.percentage);

here we have to use commas "," after each property. but you can use another style to create and initialize an object.

var john = new Object():
john.father = "raja";  //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string

How to get Locale from its String representation in Java?

There doesn't seem to be a static valueOf method for this, which is a bit surprising.

One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales(), comparing their toString values with your value.

Not very nice, but no string parsing required. You could pre-populate a Map of Strings to Locales, and look up your database string in that Map.

CheckBox in RecyclerView keeps on checking different items

I recommend that not to use checkBox.setOnCheckedChangeListener in recyclerViewAdapter. Because on scrolling recyclerView, checkBox.setOnCheckedChangeListener will be fired by adapter. It's not safe. Instead, use checkBox.setOnClickListener to interact with user inputs.

For example:

     public void onBindViewHolder(final ViewHolder holder, int position) {
        /*
         .
         .
         .
         .
         .
         .
        */

        holder.checkBoxAdapterTasks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked =  holder.checkBoxAdapterTasks.isChecked();
                if(isChecked){
                    //checkBox clicked and checked
                }else{
                    //checkBox clicked and unchecked
                }

            }
        });

    }

Cant get text of a DropDownList in code - can get value but not text

add list using

<asp:ListItem Value="United States" Text="Canada"></asp:ListItem>

and then try

DropDownList1.SelectedItem.Text

I found your mistake.

<asp:ListItem>United States</asp:ListItem> 

change this to

<asp:ListItem>United States1</asp:ListItem> 

Then you will got the actual value.

What was the issue is, there are two same values in your dropdown, when page postback, it take first value as selected and give the result accordingly. if you noticed when after postback United State Value is selected

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

TypeError: no implicit conversion of Symbol into Integer

Ive come across this many times in my work, an easy work around that I found is to ask if the array element is a Hash by class.

if i.class == Hash

    notation like i[:label] will work in this block and not throw that error

end

Use virtualenv with Python with Visual Studio Code in Ubuntu

a) Modify Visual Studio Code default virtual env path setting. It's called "python.venvPath". You do this by going into code->settings and scroll down for python settings.

b) Restart VS Code

c) Now if you do Shift + Command + P and type Python: Select Interpreter you should see list of your virtual environments.

How do I expire a PHP session after 30 minutes?

Simple way of PHP session expiry in 30 minutes.

Note : if you want to change the time, just change the 30 with your desired time and do not change * 60: this will gives the minutes.


In minutes : (30 * 60)
In days : (n * 24 * 60 * 60 ) n = no of days


Login.php

<?php
    session_start();
?>

<html>
    <form name="form1" method="post">
        <table>
            <tr>
                <td>Username</td>
                <td><input type="text" name="text"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="pwd"></td>
            </tr>
            <tr>
                <td><input type="submit" value="SignIn" name="submit"></td>
            </tr>
        </table>
    </form>
</html>

<?php
    if (isset($_POST['submit'])) {
        $v1 = "FirstUser";
        $v2 = "MyPassword";
        $v3 = $_POST['text'];
        $v4 = $_POST['pwd'];
        if ($v1 == $v3 && $v2 == $v4) {
            $_SESSION['luser'] = $v1;
            $_SESSION['start'] = time(); // Taking now logged in time.
            // Ending a session in 30 minutes from the starting time.
            $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
            header('Location: http://localhost/somefolder/homepage.php');
        } else {
            echo "Please enter the username or password again!";
        }
    }
?>

HomePage.php

<?php
    session_start();

    if (!isset($_SESSION['luser'])) {
        echo "Please Login again";
        echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
    }
    else {
        $now = time(); // Checking the time now when home page starts.

        if ($now > $_SESSION['expire']) {
            session_destroy();
            echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
        }
        else { //Starting this else one [else1]
?>
            <!-- From here all HTML coding can be done -->
            <html>
                Welcome
                <?php
                    echo $_SESSION['luser'];
                    echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
                ?>
            </html>
<?php
        }
    }
?>

LogOut.php

<?php
    session_start();
    session_destroy();
    header('Location: http://localhost/somefolder/login.php');
?>

How do I use Ruby for shell scripting?

In ruby, the constant __FILE__ will always give you the path of the script you're running.

On Linux, /usr/bin/env is your friend:

#! /usr/bin/env ruby
# Extension of this script does not matter as long
# as it is executable (chmod +x)
puts File.expand_path(__FILE__)

On Windows it depends whether or not .rb files are associated with ruby. If they are:

# This script filename must end with .rb
puts File.expand_path(__FILE__)

If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:

my_script.cmd:

@ruby %~dp0\my_script.rb

my_script.rb:

puts File.expand_path(__FILE__)

ASP.NET MVC 404 Error Handling

I've investigated A LOT on how to properly manage 404s in MVC (specifically MVC3), and this, IMHO is the best solution I've come up with:

In global.asax:

public class MvcApplication : HttpApplication
{
    protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 404)
        {
            Response.Clear();

            var rd = new RouteData();
            rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
            rd.Values["controller"] = "Errors";
            rd.Values["action"] = "NotFound";

            IController c = new ErrorsController();
            c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
        }
    }
}

ErrorsController:

public sealed class ErrorsController : Controller
{
    public ActionResult NotFound()
    {
        ActionResult result;

        object model = Request.Url.PathAndQuery;

        if (!Request.IsAjaxRequest())
            result = View(model);
        else
            result = PartialView("_NotFound", model);

        return result;
    }
}

Edit:

If you're using IoC (e.g. AutoFac), you should create your controller using:

var rc = new RequestContext(new HttpContextWrapper(Context), rd);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Errors");
c.Execute(rc);

Instead of

IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));

(Optional)

Explanation:

There are 6 scenarios that I can think of where an ASP.NET MVC3 apps can generate 404s.

Generated by ASP.NET:

  • Scenario 1: URL does not match a route in the route table.

Generated by ASP.NET MVC:

  • Scenario 2: URL matches a route, but specifies a controller that doesn't exist.

  • Scenario 3: URL matches a route, but specifies an action that doesn't exist.

Manually generated:

  • Scenario 4: An action returns an HttpNotFoundResult by using the method HttpNotFound().

  • Scenario 5: An action throws an HttpException with the status code 404.

  • Scenario 6: An actions manually modifies the Response.StatusCode property to 404.

Objectives

  • (A) Show a custom 404 error page to the user.

  • (B) Maintain the 404 status code on the client response (specially important for SEO).

  • (C) Send the response directly, without involving a 302 redirection.

Solution Attempt: Custom Errors

<system.web>
    <customErrors mode="On">
        <error statusCode="404" redirect="~/Errors/NotFound"/>
    </customErrors>
</system.web>

Problems with this solution:

  • Does not comply with objective (A) in scenarios (1), (4), (6).
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • Does not comply with objective (C).

Solution Attempt: HTTP Errors

<system.webServer>
    <httpErrors errorMode="Custom">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (A) in scenarios (2), (3), (5).
  • Does not comply with objective (B) automatically. It must be programmed manually.

Solution Attempt: HTTP Errors with Replace

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • It obscures application level http exceptions. E.g. can't use customErrors section, System.Web.Mvc.HandleErrorAttribute, etc. It can't only show generic error pages.

Solution Attempt customErrors and HTTP Errors

<system.web>
    <customErrors mode="On">
        <error statusCode="404" redirect="~/Errors/NotFound"/>
    </customError>
</system.web>

and

<system.webServer>
    <httpErrors errorMode="Custom">
        <remove statusCode="404"/>
        <error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

Problems with this solution:

  • Only works on IIS 7+.
  • Does not comply with objective (B) automatically. It must be programmed manually.
  • Does not comply with objective (C) in scenarios (2), (3), (5).

People that have troubled with this before even tried to create their own libraries (see http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3.html). But the previous solution seems to cover all the scenarios without the complexity of using an external library.

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

How to unlock android phone through ADB

Below commands works both when screen is on and off

To lock the screen:

adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26

To lock the screen and turn it off

adb shell input keyevent 82 && adb shell input keyevent 26

To unlock the screen without pass

adb shell input keyevent 82 && adb shell input keyevent 66

To unlock the screen that has pass 1234

adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66

How to allow users to check for the latest app version from inside the app?

You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941

What is the difference between CSS and SCSS?

Sass is a language that provides features to make it easier to deal with complex styling compared to editing raw .css. An example of such a feature is allowing definition of variables that can be re-used in different styles.

The language has two alternative syntaxes:

  • A JSON like syntax that is kept in files ending with .scss
  • A YAML like syntax that is kept in files ending with .sass

Either of these must be compiled to .css files which are recognized by browsers.

See https://sass-lang.com/ for further information.

Can I pass parameters by reference in Java?

I don't think you can. Your best option might be to encapsulate the thing you want to pass "by ref" onto another class instance, and pass the (outer) class's reference (by value). If you see what I mean...

i.e. your method changes the internal state of the object it is passed, which is then visible to the caller.

How do emulators work and how are they written?

Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.

The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.

jQuery see if any or no checkboxes are selected

You can use something like this

if ($("#formID input:checkbox:checked").length > 0)
{
    // any one is checked
}
else
{
   // none is checked
}

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Another possible solution to this error that I found. Might not have answered OP's exact question but may help others who stumble across this error message.

I was creating my Client in code using WebHttpBinding, in order to replicate the following line:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>

I had to do:

var binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows;

as well as setting proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

How do I check if PHP is connected to a database already?

// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();

// Later....
if (flag_is_set())
 mysql_connect(....);

Why when I transfer a file through SFTP, it takes longer than FTP?

UPDATE: As a commenter pointed out, the problem I outline below was fixed some time before this post. However, I knew of the HP-SSH project and I asked the author to weigh in. As they explain in the (rightfully) most upvoted answer, encryption is not the source of the problem. Yay for email and people smarter than myself!

Wow, a year-old question with nothing but incorrect answers. However, I must admit that I assumed the slowdown was due to encryption when I asked myself the same question. But ask yourself the next logical question: how quickly can your computer encrypt and decrypt data? If you think that rate is anywhere near the 4.5Mb/second reported by the OP (.5625MBs or roughly half the capacity of a 5.5" floppy disk!) smack yourself a few times, drink some coffee, and ask yourself the same question again.

It apparently has to do with what amounts to be an oversight in the packet size selection, or at least that's what the author of LIBSSH2 says,

The nature of SFTP and its ACK for every small data chunk it sends, makes an initial naive SFTP implementation suffer badly when sending data over high latency networks. If you have to wait a few hundred milliseconds for each 32KB of data then there will never be fast SFTP transfers. This sort of naive implementation is what libssh2 has offered up until and including libssh2 1.2.7.

So the speed hit is due to tiny packet sizes x mandatory ack responses for each packet, which is clearly insane.

The High Performance SSH/SCP (HP-SSH) project provides an OpenSSH patch set which apparently improves the internal buffers as well as parallelizing encryption. Note, however, that even the non-parallelized versions ran at speeds above the 40Mb/s unencrypted speeds obtained by some commenters. The fix involves changing the way in which OpenSSH was calling the encryption libraries, NOT the cipher and there is zero difference in speed between AES128 and AES256. Encryption takes some time, but it is marginal. It might have mattered back in the 90's but (like the speed of Java vs C) it just doesn't matter anymore.

How to access Spring MVC model object in javascript file?

You can't access java objects from JavaScript because there are no objects on client side. It only receives plain HTML page (hidden fields can help but it's not very good approach).

I suggest you to use ajax and @ResponseBody.

Close Bootstrap Modal

$("#your-modal-id").modal('hide');

Running this call via class ($(".my-modal")) won't work.

How do I POST urlencoded form data with $http without jQuery?

The problem is the JSON string format, You can use a simple URL string in data:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});

Can Google Chrome open local links?

This question is dated, but I had the same problem just now, the solution I found was to map a virtual directory in IIS to the networked drive with the documents, so the url became a friendly "http://" address.

Setting virtual directories:

IIS:

http://www.iis.net/configreference/system.applicationhost/sites/site/application/virtualdirectory

Apache:

http://w3shaman.com/article/creating-virtual-directory-apache

Cheers!

The performance impact of using instanceof in Java

I just made a simple test to see how instanceOf performance is comparing to a simple s.equals() call to a string object with only one letter.

in a 10.000.000 loop the instanceOf gave me 63-96ms, and the string equals gave me 106-230ms

I used java jvm 6.

So in my simple test is faster to do a instanceOf instead of a one character string comparison.

using Integer's .equals() instead of string's gave me the same result, only when I used the == i was faster than instanceOf by 20ms (in a 10.000.000 loop)

How to add a string to a string[] array? There's no .Add function

This code works great for preparing the dynamic values Array for spinner in Android:

    List<String> yearStringList = new ArrayList<>();
    yearStringList.add("2017");
    yearStringList.add("2018");
    yearStringList.add("2019");


    String[] yearStringArray = (String[]) yearStringList.toArray(new String[yearStringList.size()]);

Swipe ListView item From right to left show delete button

I had created a demo on my github which includes on swiping from right to left a delete button will appear and you can then delete your item from the ListView and update your ListView.

how to upload a file to my server using html

On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.

Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

Find closest previous element jQuery

see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());

see http://jsfiddle.net/gBwLq/

How to check edittext's text is email address or not?

With android.util.Patterns and Kotlin it's very simple. One line function which return Boolean value.

fun validateEmail(email: String) = Patterns.EMAIL_ADDRESS.matcher(email)

How to calculate number of days between two given dates?

Days until Christmas:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

More arithmetic here.

Add leading zeroes/0's to existing Excel values to certain length

Even this will work nicely

REPT(0,2-LEN(F2)&F2

where 2 is total number of digits, for 0 ~ 9 -> it will display 00 to 09 rest nothing will be added.

How can I read a text file in Android?

First you store your text file in to raw folder.

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2)
                continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
    Log.d(TAG, "DONE loading words.");
}

How to remove non-alphanumeric characters?

[\W_]+

 

$string = preg_replace("/[\W_]+/u", '', $string);

It select all not A-Z, a-z, 0-9 and delete it.

See example here: https://regexr.com/3h1rj

Testing whether a value is odd or even

A simple modification/improvement of Steve Mayne answer!

function isEvenOrOdd(n){
    if(n === parseFloat(n)){
        return isNumber(n) && (n % 2 == 0);
    }
    return false;
}

Note: Returns false if invalid!

How does DISTINCT work when using JPA and Hibernate

Depending on the underlying JPQL or Criteria API query type, DISTINCT has two meanings in JPA.

Scalar queries

For scalar queries, which return a scalar projection, like the following query:

List<Integer> publicationYears = entityManager
.createQuery(
    "select distinct year(p.createdOn) " +
    "from Post p " +
    "order by year(p.createdOn)", Integer.class)
.getResultList();

LOGGER.info("Publication years: {}", publicationYears);

The DISTINCT keyword should be passed to the underlying SQL statement because we want the DB engine to filter duplicates prior to returning the result set:

SELECT DISTINCT
    extract(YEAR FROM p.created_on) AS col_0_0_
FROM
    post p
ORDER BY
    extract(YEAR FROM p.created_on)

-- Publication years: [2016, 2018]

Entity queries

For entity queries, DISTINCT has a different meaning.

Without using DISTINCT, a query like the following one:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();

LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

is going to JOIN the post and the post_comment tables like this:

SELECT p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'

-- Fetched the following Post entity identifiers: [1, 1]

But the parent post records are duplicated in the result set for each associated post_comment row. For this reason, the List of Post entities will contain duplicate Post entity references.

To eliminate the Post entity references, we need to use DISTINCT:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

But then DISTINCT is also passed to the SQL query, and that's not desirable at all:

SELECT DISTINCT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

By passing DISTINCT to the SQL query, the EXECUTION PLAN is going to execute an extra Sort phase which adds overhead without bringing any value since the parent-child combinations always return unique records because of the child PK column:

Unique  (cost=23.71..23.72 rows=1 width=1068) (actual time=0.131..0.132 rows=2 loops=1)
  ->  Sort  (cost=23.71..23.71 rows=1 width=1068) (actual time=0.131..0.131 rows=2 loops=1)
        Sort Key: p.id, pc.id, p.created_on, pc.post_id, pc.review
        Sort Method: quicksort  Memory: 25kB
        ->  Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.054..0.058 rows=2 loops=1)
              Hash Cond: (pc.post_id = p.id)
              ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.010..0.010 rows=2 loops=1)
              ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.027..0.027 rows=1 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.017..0.018 rows=1 loops=1)
                          Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
                          Rows Removed by Filter: 3
Planning time: 0.227 ms
Execution time: 0.179 ms

Entity queries with HINT_PASS_DISTINCT_THROUGH

To eliminate the Sort phase from the execution plan, we need to use the HINT_PASS_DISTINCT_THROUGH JPA query hint:

List<Post> posts = entityManager
.createQuery(
    "select distinct p " +
    "from Post p " +
    "left join fetch p.comments " +
    "where p.title = :title", Post.class)
.setParameter(
    "title", 
    "High-Performance Java Persistence eBook has been released!"
)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();
 
LOGGER.info(
    "Fetched the following Post entity identifiers: {}", 
    posts.stream().map(Post::getId).collect(Collectors.toList())
);

And now, the SQL query will not contain DISTINCT but Post entity reference duplicates are going to be removed:

SELECT
       p.id AS id1_0_0_,
       pc.id AS id1_1_1_,
       p.created_on AS created_2_0_0_,
       p.title AS title3_0_0_,
       pc.post_id AS post_id3_1_1_,
       pc.review AS review2_1_1_,
       pc.post_id AS post_id3_1_0__
FROM   post p
LEFT OUTER JOIN
       post_comment pc ON p.id=pc.post_id
WHERE
       p.title='High-Performance Java Persistence eBook has been released!'
 
-- Fetched the following Post entity identifiers: [1]

And the Execution Plan is going to confirm that we no longer have an extra Sort phase this time:

Hash Right Join  (cost=11.76..23.70 rows=1 width=1068) (actual time=0.066..0.069 rows=2 loops=1)
  Hash Cond: (pc.post_id = p.id)
  ->  Seq Scan on post_comment pc  (cost=0.00..11.40 rows=140 width=532) (actual time=0.011..0.011 rows=2 loops=1)
  ->  Hash  (cost=11.75..11.75 rows=1 width=528) (actual time=0.041..0.041 rows=1 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        ->  Seq Scan on post p  (cost=0.00..11.75 rows=1 width=528) (actual time=0.036..0.037 rows=1 loops=1)
              Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
              Rows Removed by Filter: 3
Planning time: 1.184 ms
Execution time: 0.160 ms

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

according to GSON User guide, you cannot.

Collections Limitations

Can serialize collection of arbitrary objects but can not deserialize from it. Because there is no way for the user to indicate the type of the resulting object

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Convert List to Pandas Dataframe Column

For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.

There are Different Ways to Perform the Above Operation.

import pandas as pd

  1. pd.DataFrame({'Column_Name':Column_Data})
  • Column_Name : String
  • Column_Data : List Form
  1. Data = pd.DataFrame(Column_Data)

    Data.columns = ['Column_Name']

So, for the above mentioned issue, the code snippet is

import pandas as pd

Content = ['Thanks You',
           'Its fine no problem',
           'Are you sure']

Data = pd.DataFrame({'Text': Content})

How to use default Android drawables

Better you copy and move them to your own resources. Some resources might not be available on previous Android versions. Here is a link with all drawables available on each Android version thanks to @fiXedd

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

Rank function in MySQL

To avoid the "however" in Erandac's answer in combination of Daniel's and Salman's answers, one may use one of the following "partition workarounds"

SELECT customerID, myDate

  -- partition ranking works only with CTE / from MySQL 8.0 on
  , RANK() OVER (PARTITION BY customerID ORDER BY dateFrom) AS rank, 

  -- Erandac's method in combination of Daniel's and Salman's
  -- count all items in sequence, maximum reaches row count.
  , IF(customerID=@_lastRank, @_curRank:=@_curRank, @_curRank:=@_sequence+1) AS sequenceRank
  , @_sequence:=@_sequence+1 as sequenceOverAll

  -- Dense partition ranking, works also with MySQL 5.7
  -- remember to set offset values in from clause
  , IF(customerID=@_lastRank, @_nxtRank:=@_nxtRank, @_nxtRank:=@_nxtRank+1 ) AS partitionRank
  , IF(customerID=@_lastRank, @_overPart:=@_overPart+1, @_overPart:=1 ) AS partitionSequence

  , @_lastRank:=customerID
FROM myCustomers, 
  (SELECT @_curRank:=0, @_sequence:=0, @_lastRank:=0, @_nxtRank:=0, @_overPart:=0 ) r
ORDER BY customerID, myDate

The partition ranking in the 3rd variant in this code snippet will return continous ranking numbers. this will lead to a data structur similar to the rank() over partition by result. As an example, see below. In particular, the partitionSequence will always start with 1 for each new partitionRank, using this method:

customerID    myDate   sequenceRank (Erandac)
                          |    sequenceOverAll
                          |     |   partitionRank
                          |     |     | partitionSequence
                          |     |     |    | lastRank
... lines ommitted for clarity
40    09.11.2016 11:19    1     44    1   44    40
40    09.12.2016 12:08    1     45    1   45    40
40    09.12.2016 12:08    1     46    1   46    40
40    09.12.2016 12:11    1     47    1   47    40
40    09.12.2016 12:12    1     48    1   48    40
40    13.10.2017 16:31    1     49    1   49    40
40    15.10.2017 11:00    1     50    1   50    40
76    01.07.2015 00:24    51    51    2    1    76
77    04.08.2014 13:35    52    52    3    1    77
79    15.04.2015 20:25    53    53    4    1    79
79    24.04.2018 11:44    53    54    4    2    79
79    08.10.2018 17:37    53    55    4    3    79
117   09.07.2014 18:21    56    56    5    1   117
119   26.06.2014 13:55    57    57    6    1   119
119   02.03.2015 10:23    57    58    6    2   119
119   12.10.2015 10:16    57    59    6    3   119
119   08.04.2016 09:32    57    60    6    4   119
119   05.10.2016 12:41    57    61    6    5   119
119   05.10.2016 12:42    57    62    6    6   119
...

How can I manually generate a .pyc file from a .py file

There is two way to do this

  1. Command line
  2. Using python program

If you are using command line use python -m compileall <argument> to compile python code to python binary code. Ex: python -m compileall -x ./*

Or, You can use this code to compile your library into byte-code.

import compileall
import os

lib_path = "your_lib_path"
build_path = "your-dest_path"

compileall.compile_dir(lib_path, force=True, legacy=True)

def moveToNewLocation(cu_path):
    for file in os.listdir(cu_path):
        if os.path.isdir(os.path.join(cu_path, file)):
            compile(os.path.join(cu_path, file))
        elif file.endswith(".pyc"):
            dest = os.path.join(build_path, cu_path ,file)
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            os.rename(os.path.join(cu_path, file), dest)

moveToNewLocation(lib_path)

look at ? docs.python.org for detailed documentation

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

PHP - Get bool to echo false when false

json_encode will do it out-of-the-box, but it's not pretty (indented, etc):

echo json_encode(array('whatever' => TRUE, 'somethingelse' => FALSE));

...gives...

{"whatever":true,"somethingelse":false}

How do I call a function twice or more times consecutively?

from itertools import repeat, starmap

results = list(starmap(do, repeat((), 3)))

See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:

for _ in starmap(do, repeat((), 3)): pass

but that's getting ugly.

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

First off: My problem isn't the exact same as yours, but this post is the first thing that comes up in google for the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' error at the time I wrote this. The solution may be useful to people searching for this error as I did not find this specific solution anywhere online.

In my case, I used Xampp/Apache and PHP sqlsrv to try to connect to an MSSQL database using Windows Authentication and received the Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' error you described. I finally found the problem to be the Apache service itself running under the user "LOCAL SERVICE" instead of the user account I was logged in as. In other words, it literally was using an anonymous account. The solution was to go into services.msc, right click the Apache service, go to Properties, go to the Log On tab, and enter the credentials for the user. This falls in line with your problem related to SPN's as your SPN's are set up to run from a specific user on the domain. So if the correct SPN is not running, windows authentication will default to the wrong user (likely the "LOCAL SERVICE" user) and give you the Anonymous error.

Here's where it's different from your problem. None of the computers on the local network are on a Domain, they are only on a Workgroup. To use Windows Authentication with a Workgroup, both the computer with the server (in my case MSSQL Server) and the computer with the service requesting data (in my case Apache) needed to have a user with an identical name and identical password.

To summarize, The Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' error in both our cases seems to be caused by a service not running and/or not on the right user. Ensuring the right SPN or other Service is running and under the correct user should solve the anonymous part of the problem.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Java error: Comparison method violates its general contract

You can use the following class to pinpoint transitivity bugs in your Comparators:

/**
 * @author Gili Tzabari
 */
public final class Comparators
{
    /**
     * Verify that a comparator is transitive.
     *
     * @param <T>        the type being compared
     * @param comparator the comparator to test
     * @param elements   the elements to test against
     * @throws AssertionError if the comparator is not transitive
     */
    public static <T> void verifyTransitivity(Comparator<T> comparator, Collection<T> elements)
    {
        for (T first: elements)
        {
            for (T second: elements)
            {
                int result1 = comparator.compare(first, second);
                int result2 = comparator.compare(second, first);
                if (result1 != -result2)
                {
                    // Uncomment the following line to step through the failed case
                    //comparator.compare(first, second);
                    throw new AssertionError("compare(" + first + ", " + second + ") == " + result1 +
                        " but swapping the parameters returns " + result2);
                }
            }
        }
        for (T first: elements)
        {
            for (T second: elements)
            {
                int firstGreaterThanSecond = comparator.compare(first, second);
                if (firstGreaterThanSecond <= 0)
                    continue;
                for (T third: elements)
                {
                    int secondGreaterThanThird = comparator.compare(second, third);
                    if (secondGreaterThanThird <= 0)
                        continue;
                    int firstGreaterThanThird = comparator.compare(first, third);
                    if (firstGreaterThanThird <= 0)
                    {
                        // Uncomment the following line to step through the failed case
                        //comparator.compare(first, third);
                        throw new AssertionError("compare(" + first + ", " + second + ") > 0, " +
                            "compare(" + second + ", " + third + ") > 0, but compare(" + first + ", " + third + ") == " +
                            firstGreaterThanThird);
                    }
                }
            }
        }
    }

    /**
     * Prevent construction.
     */
    private Comparators()
    {
    }
}

Simply invoke Comparators.verifyTransitivity(myComparator, myCollection) in front of the code that fails.

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

Checking host availability by using ping in bash scripts

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

How do you create a UIImage View Programmatically - Swift

You can use above in one line.

  let imageView = UIImageView(image: UIImage(named: "yourImage.png")!)

How to add external fonts to android application

You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()

TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);

Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).

Pod install is staying on "Setting up CocoaPods Master repo"

This happens only once.

  • Master repo has +-1GB (November 2016).

  • To track the progress you can use activity monitor app and look for git-remote-https.

  • Next time it (pod setup or pod repo update) will only fast update all spec-repos in ~/.cocoapods/repos.

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

Edit line thickness of CSS 'underline' attribute

Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.

_x000D_
_x000D_
<span style="font-size:1em;text-decoration:underline;">_x000D_
 <span style="font-size:1.5em;">_x000D_
   Text with big font size and thin underline_x000D_
 </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Which versions of SSL/TLS does System.Net.WebRequest support?

I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.

If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.

SQL SERVER DATETIME FORMAT

This is my favorite use of 112 and 114

select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate() 

112 + 114 or YYYYMMDDHHMMSSMSS'

Result:

Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS

20171016083349100

How do you create a dropdownlist from an enum in ASP.NET MVC?

In ASP.NET MVC 5.1, they added the EnumDropDownListFor() helper, so no need for custom extensions:

Model:

public enum MyEnum
{
    [Display(Name = "First Value - desc..")]
    FirstValue,
    [Display(Name = "Second Value - desc...")]
    SecondValue
}

View:

@Html.EnumDropDownListFor(model => model.MyEnum)

Using Tag Helper (ASP.NET MVC 6):

<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Using some text manipulation we can separate each unit of time and then sum them together with their millisecond coefficients.

To show the formulas in the cells use CTRL + `


Raw data view


Formula view

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

Here is the answer.

System.exit(0);// normal termination - Successful - zero
System.exit(-1);//Exit with some Error
System.exit(1);//one or any positive integer // exit with some Information message

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

%S seems to conform to The Single Unix Specification v2 and is also part of the current (2008) POSIX specification.

Equivalent C99 conforming format specifiers would be %s and %ls.

Creating an array of objects in Java

This is correct.

A[] a = new A[4];

...creates 4 A references, similar to doing this:

A a1;
A a2;
A a3;
A a4;

Now you couldn't do a1.someMethod() without allocating a1 like this:

a1 = new A();

Similarly, with the array you need to do this:

a[0] = new A();

...before using it.

How to force remounting on React components?

Change the key of the component.

<Component key="1" />
<Component key="2" />

Component will be unmounted and a new instance of Component will be mounted since the key has changed.

edit: Documented on You Probably Don't Need Derived State:

When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.

How can I rename a field for all documents in MongoDB?

You can use:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Or you can use the former way:

remap = function (x) {
  if (x.additional){
    db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
  }
}

db.foo.find().forEach(remap);

In MongoDB 3.2 you can also use

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )

The general syntax of this is

db.collection.updateMany(filter, update, options)

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

NSRange to Range<String.Index>

You need to use Range<String.Index> instead of the classic NSRange. The way I do it (maybe there is a better way) is by taking the string's String.Index a moving it with advance.

I don't know what range you are trying to replace, but let's pretend you want to replace the first 2 characters.

var start = textField.text.startIndex // Start at the string's start index
var end = advance(textField.text.startIndex, 2) // Take start index and advance 2 characters forward
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)

textField.text.stringByReplacingCharactersInRange(range, withString: string)

How do I force git to use LF instead of CR+LF under windows?

core.autocrlf=input is the right setting for what you want, but you might have to do a git update-index --refresh and/or a git reset --hard for the change to take effect.

With core.autocrlf set to input, git will not apply newline-conversion on check-out (so if you have LF in the repo, you'll get LF), but it will make sure that in case you mess up and introduce some CRLFs in the working copy somehow, they won't make their way into the repo.

How to do a non-greedy match in grep?

I know that its a bit of a dead post but I just noticed that this works. It removed both clean-up and cleanup from my output.

> grep -v -e 'clean\-\?up'
> grep --version grep (GNU grep) 2.20

Replace a string in a file with nodejs

You can also use the 'sed' function that's part of ShellJS ...

 $ npm install [-g] shelljs


 require('shelljs/global');
 sed('-i', 'search_pattern', 'replace_pattern', file);

Visit ShellJs.org for more examples.

Sublime Text 2: How do I change the color that the row number is highlighted?

This post is for Sublime 3.

I just installed Sublime 3, the 64 bit version, on Ubuntu 14.04. I can't tell the difference between this version and Sublime 2 as far as user interface. The reason I didn't go with Sublime 2 is that it gives an annoying "GLib critical" error messages.

Anyways - previous posts mentioned the file /sublime_text_3/Packages/Color\ Scheme\ -\ Default.sublime-package

I wanted to give two tips here with respect to this file in Sublime 3:

  1. You can edit it with pico and use ^W to search the theme name. The first search result will bring you to an XML style entry where you can change the values. Make a copy before you experiment.
  2. If you choose the theme in the sublime menu (under Preferences/Color Scheme) before you change this file, then the changes will be cached and your change will not take effect. So delete the cached version and restart sublime for the changes to take effect. The cached version is at ~/.config/sublime-text-3/Cache/Color Scheme - Default/

Py_Initialize fails - unable to load the file system codec

In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH, they all work fine

Remove tracking branches no longer on remote

You could do this:

git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -d

P.S.: as pointed out by Sam H.

execute this first:

git remote prune origin

Examples for string find in Python

Try this:

with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
    p = file.read(bsize).find(SEARCH_WORD)
    if p > -1:
        pos_dec = file.tell() - (bsize - p)
        file.seek(pos_dec + word_len)
        bsize = fsize - file.tell()
    if file.tell() < fsize:
        seek = file.tell() - word_len + 1
        file.seek(seek)
    else:
        break

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to set locale in DatePipe in Angular 2?

This might be a little bit late, but in my case (angular 6), I created a simple pipe on top of DatePipe, something like this:

private _regionSub: Subscription;
private _localeId: string;

constructor(private _datePipe: DatePipe, private _store: Store<any>) {
  this._localeId = 'en-AU';
  this._regionSub = this._store.pipe(select(selectLocaleId))
    .subscribe((localeId: string) => {
      this._localeId = localeId || 'en-AU';
    });
}

ngOnDestroy() { // Unsubscribe }

transform(value: string | number, format?: string): string {
  const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
  return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}

May not be the best solution, but simple and works.

Xcode Objective-C | iOS: delay function / NSTimer help?

A slightly less verbose way is to use the performSelector: withObject: afterDelay: which sets up the NSTimer object for you and can be easily cancelled

So continuing with the previous example this would be

[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];

More info in the doc

Is there a way to define a min and max value for EditText in Android?

I extended @Pratik Sharmas code to use BigDecimal objects instead of ints so that it can accept larger numbers, and account for any formatting in the EditText that isn't a number (like currency formatting i.e. spaces, commas and periods)

EDIT: note that this implementation has 2 as the minimum significant figures set on the BigDecimal (see the MIN_SIG_FIG constant) as I used it for currency, so there was always 2 leading numbers before the decimal point. Alter the MIN_SIG_FIG constant as necessary for your own implementation.

public class InputFilterMinMax implements InputFilter {
private static final int MIN_SIG_FIG = 2;
private BigDecimal min, max;

public InputFilterMinMax(BigDecimal min, BigDecimal max) {
    this.min = min;
    this.max = max;
}

public InputFilterMinMax(String min, String max) {
    this.min = new BigDecimal(min);
    this.max = new BigDecimal(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
        int dend) {
    try {
        BigDecimal input = formatStringToBigDecimal(dest.toString()
                + source.toString());

        if (isInRange(min, max, input)) {

            return null;
        }
    } catch (NumberFormatException nfe) {

    }
    return "";
}

private boolean isInRange(BigDecimal a, BigDecimal b, BigDecimal c) {
    return b.compareTo(a) > 0 ? c.compareTo(a) >= 0 && c.compareTo(b) <= 0
            : c.compareTo(b) >= 0 && c.compareTo(a) <= 0;
}

public static BigDecimal formatStringToBigDecimal(String n) {

    Number number = null;
    try {
        number = getDefaultNumberFormat().parse(n.replaceAll("[^\\d]", ""));

        BigDecimal parsed = new BigDecimal(number.doubleValue()).divide(new BigDecimal(100), 2,
                BigDecimal.ROUND_UNNECESSARY);
        return parsed;
    } catch (ParseException e) {
        return new BigDecimal(0);
    }
}

private static NumberFormat getDefaultNumberFormat() {
    NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
    nf.setMinimumFractionDigits(MIN_SIG_FIG);
    return nf;
}

What is the right way to populate a DropDownList from a database?

public void getClientNameDropDowndata()
{
    getConnection = Connection.SetConnection(); // to connect with data base Configure manager
    string ClientName = "Select  ClientName from Client ";
    SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
    ClientNameCommand.CommandType = CommandType.Text;
    SqlDataReader ClientNameData;
    ClientNameData = ClientNameCommand.ExecuteReader();
    if (ClientNameData.HasRows)
    {
        DropDownList_ClientName.DataSource = ClientNameData;
        DropDownList_ClientName.DataValueField = "ClientName";
        DropDownList_ClientName.DataTextField="ClientName";
        DropDownList_ClientName.DataBind();
    }
    else
    {
        MessageBox.Show("No is found");
        CloseConnection = new Connection();
        CloseConnection.closeConnection(); // close the connection 
    }
}

Linq filter List<string> where it contains a string value from another List<string>

its even easier:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

JavaScript closure inside loops – simple practical example

Ok. I read through all of the answers. Even though there is a good explanation here - I just could not get this to work. So I went looking on the internet. The person at https://dzone.com/articles/why-does-javascript-loop-only-use-last-value had an answer which is not presented here. So I thought I'd post a short example. This made a lot more sense to me.

The long and short of it is that the LET command is nice but is only now being used. HOWEVER, the LET command is really just a TRY-CATCH combo. This works all the way back to IE3 (I believe). Using the TRY-CATCH combo - life is simple and good. Probably why the EMCScript people decided to use it. It also does not need a setTimeout() function. So no time is lost. Basically, you need one TRY-CATCH combo per FOR loop. Here is an example:

    for( var i in myArray ){
       try{ throw i }
       catch(ii){
// Do whatever it is you want to do with ii
          }
       }

If you have more than one FOR loop, you just put a TRY-CATCH combo for each one. Also, personally, I always use the double letter of whatever FOR variable I am using. So "ii" for "i" and so on. I am using this technique in a routine to send mouseover commands to a different routine.

putting datepicker() on dynamically created elements - JQuery/JQueryUI

$( ".datepicker_recurring_start" ).each(function(){
    $(this).datepicker({
        dateFormat:"dd/mm/yy",
        yearRange: '2000:2012',
        changeYear: true,
        changeMonth: true
    });
});

json call with C#

Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):

public static bool SendAnSMSMessage(string message)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";

    var serializer = new Newtonsoft.Json.JsonSerializer();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
        {
             serializer.Serialize(tw, 
                 new {method= "send",
                      @params = new string[]{
                          "IPutAGuidHere", 
                          "[email protected]",
                          "MyTenDigitNumberWasHere",
                          message
                      }});
        }
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        //Now you have your response.
        //or false depending on information in the response
        return true;        
    }
}

Convert a tensor to numpy array in Tensorflow?

To convert back from tensor to numpy array you can simply run .eval() on the transformed tensor.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

Can You Get A Users Local LAN IP Address Via JavaScript?

Chrome 76+

Last year I used Linblow's answer (2018-Oct-19) to successfully discover my local IP via javascript. However, recent Chrome updates (76?) have wonked this method so that it now returns an obfuscated IP, such as: 1f4712db-ea17-4bcf-a596-105139dfd8bf.local

If you have full control over your browser, you can undo this behavior by turning it off in Chrome Flags, by typing this into your address bar:

chrome://flags

and DISABLING the flag Anonymize local IPs exposed by WebRTC

In my case, I require the IP for a TamperMonkey script to determine my present location and do different things based on my location. I also have full control over my own browser settings (no Corporate Policies, etc). So for me, changing the chrome://flags setting does the trick.

Sources:

https://groups.google.com/forum/#!topic/discuss-webrtc/6stQXi72BEU

https://codelabs.developers.google.com/codelabs/webrtc-web/index.html

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

How to detect a mobile device with JavaScript?

A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px)  {
    #hoofdcollumn {margin: 10px 5%; width:90%}
}

Hope this helps!

How do I pass multiple ints into a vector at once?

Try pass array to vector:

int arr[] = {2,5,8,11,14};
std::vector<int> TestVector(arr, arr+5);

You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.

If you use C++11, you can try:

std::vector<int> v{2,5,8,11,14};

Or

 std::vector<int> v = {2,5,8,11,14};

Radio/checkbox alignment in HTML/CSS

If your label is long and goes on multiple rows setting the width and display:inline-block will help.

.form-field * {
  vertical-align: middle;
}
.form-field input {
  clear:left;
}
.form-field label { 
  width:200px;
  display:inline-block;
}

<div class="form-field">
    <input id="option1" type="radio" name="opt" value="1"/>
    <label for="option1">Option 1 is very long and is likely to go on two lines.</label>
    <input id="option2" type="radio" name="opt" value="2"/>
    <label for="option2">Option 2 might fit into one line.</label>
</div>

Removing App ID from Developer Connection

Does deleting the AppID do anything to disable versions of an Enterprise distributed app "in the wild" ??

If not, is there any way to kill off an Enterprise app before it's expiry?

Dynamically updating css in Angular 2

Try this

 <div class="home-component" 
 [style.width.px]="width" 
 [style.height.px]="height">Some stuff in this div</div>

[Updated]: To set in % use

[style.height.%]="height">Some stuff in this div</div>

What is the proper way to comment functions in Python?

While I agree that this should not be a comment, but a docstring as most (all?) answers suggest, I want to add numpydoc (a docstring style guide).

If you do it like this, you can (1) automatically generate documentation and (2) people recognize this and have an easier time to read your code.

How to redirect a url in NGINX

First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library

How to install pcre library

If the above mentioned are done or if you already have them, then just add the below code in your nginx server block

  if ($host !~* ^www\.) {
    rewrite ^(.*)$ http://www.$host$1 permanent;
  }

To remove www from every request you can use

  if ($host = 'www.your_domain.com' ) {
   rewrite  ^/(.*)$  http://your_domain.com/$1  permanent;
  }

so your server block will look like

  server {
            listen       80;
            server_name  test.com;
            if ($host !~* ^www\.) {
                    rewrite ^(.*)$ http://www.$host$1 permanent;
            }
            client_max_body_size   10M;
            client_body_buffer_size   128k;

            root       /home/test/test/public;
            passenger_enabled on;
            rails_env production;

            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                    root   html;
            }
    }

Is there any publicly accessible JSON data source to test with real world data?

Found one from Flickr that doesn't need registration / api.

Basic sample, Fiddle: http://jsfiddle.net/Braulio/vDr36/

More info: post

Pasted sample

HTML

<div id="images">

</div>

Javascript

// Querystring, "tags" search term, comma delimited
var query = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?";


// This function is called once the call is satisfied
// http://stackoverflow.com/questions/13854250/understanding-cross-domain-xhr-and-xml-data
var mycallback = function (data) {

    // Start putting together the HTML string
    var htmlString = "";

    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){

        // I only want the ickle square thumbnails
        var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");

        // Here's where we piece together the HTML
        htmlString += '<li><a href="' + item.link + '" target="_blank">';
        htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
        htmlString += '" alt="'; htmlString += item.title + '" />';
        htmlString += '</a></li>';

    });

    // Pop our HTML in the #images DIV
    $('#images').html(htmlString);
};


// Ajax call to retrieve data
$.getJSON(query, mycallback);

Another very interesting is Star Wars Rest API:

https://swapi.co/

generating variable names on fly in python

bit long, it works i guess...

prices = [5, 12, 45]
names = []
for i, _ in enumerate(prices):
    names.append("price"+str(i+1))
dict = {}
for name, price in zip(names, prices):
    dict[name] = price
for item in dict:
    print(item, "=", dict[item])

What is the symbol for whitespace in C?

There is no particular symbol for whitespace. It is actually a set of some characters which are:

' '      space 
'\t'     horizontal tab 
'\n'     newline
'\v'     vertical tab 
'\f'     feed 
'\r'     carriage return    

Use isspace standard library function from ctype.h if you want to check for any of these white-spaces.

For just a space, use ' '.

How to run bootRun with spring profile via gradle task

For those folks using Spring Boot 2.0+, you can use the following to setup a task that will run the app with a given set of profiles.

task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') {
    group = 'Application'

    doFirst() {
        main = bootJar.mainClassName
        classpath = sourceSets.main.runtimeClasspath
        systemProperty 'spring.profiles.active', 'dev'
    }
}

Then you can simply run ./gradlew bootRunDev or similar from your IDE.

How to convert string to Title Case in Python?

def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

Add new value to an existing array in JavaScript

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

How to find/identify large commits in git history?

I stumbled across this for the same reason as anyone else. But the quoted scripts didn't quite work for me. I've made one that is more a hybrid of those I've seen and it now lives here - https://gitlab.com/inorton/git-size-calc

Iterate over object keys in node.js

adjust his code:

Object.prototype.each = function(iterateFunc) {
        var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
        var that = this;
        var next = function() {

            if (counter < len) {
                currentKey = keys[counter++];
                iterateFunc(currentKey, that[currentKey]);

                next();
            } else {
                that = counter = keys = currentKey = len = next = undefined;
            }
        };
        next();
    };

    ({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
        // do things
        console.log(key);
    });

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

See other answers if you want to share a global variable across modules.

JOptionPane Yes or No window

Code for Yes and No Message

      int n = JOptionPane.showConfirmDialog(  
                null,
                "sample question?!" ,
                "",
                JOptionPane.YES_NO_OPTION);

      if(n == JOptionPane.YES_OPTION)
      {
          JOptionPane.showMessageDialog(null, "Opening...");
      }
      else
      {
          JOptionPane.showMessageDialog(null, "Goodbye");
          System.exit(0);

Apply function to each element of a list

I think you mean to use map instead of filter:

>>> from string import upper
>>> mylis=['this is test', 'another test']
>>> map(upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']

Even simpler, you could use str.upper instead of importing from string (thanks to @alecxe):

>>> map(str.upper, mylis)
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, map constructs a new list by applying a given function to every element in a list. filter constructs a new list by restricting to elements that evaluate to True with a given function.

In Python 3.x, map and filter construct iterators instead of lists, so if you are using Python 3.x and require a list the list comprehension approach would be better suited.

How to use if statements in underscore.js templates?

Depending on the situation and or your style, you might also wanna use print inside your <% %> tags, as it allows for direct output. Like:

<% if (typeof(id) != "undefined") {
     print(id);
}
else {
    print('new Model');
} %>

And for the original snippet with some concatenation:

<% if (typeof(date) != "undefined") {
    print('<span class="date">' + date + '</span>');
} %>

Programmatically get own phone number in iOS

AppStore will reject it, as it's reaching outside of application container.

Apps should be self-contained in their bundles, and may not read or write data outside the designated container area

Section 2.5.2 : https://developer.apple.com/app-store/review/guidelines/#software-requirements

jquery data selector

You can also use a simple filtering function without any plugins. This is not exactly what you want but the result is the same:

$('a').data("user", {name: {first:"Tom",last:"Smith"},username: "tomsmith"});

$('a').filter(function() {
    return $(this).data('user') && $(this).data('user').name.first === "Tom";
});

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

Insert into C# with SQLCommand

you can use implicit casting AddWithValue

cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);

sample code,

using (SqlConnection conn = new SqlConnection("connectionString")) 
{
    using (SqlCommand cmd = new SqlCommand()) 
    { 
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = @"INSERT INTO klant(klant_id,naam,voornaam) 
                            VALUES(@param1,@param2,@param3)";  

        cmd.Parameters.AddWithValue("@param1", klantId);  
        cmd.Parameters.AddWithValue("@param2", klantNaam);  
        cmd.Parameters.AddWithValue("@param3", klantVoornaam);  

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery(); 
        }
        catch(SqlException e)
        {
            MessgeBox.Show(e.Message.ToString(), "Error Message");
        }

    } 
}

Passing an array of parameters to a stored procedure

I like this one, because it is suited to be passed as an XElement, which is suitable for SqlCommand

(Sorry it is VB.NET but you get the idea)

<Extension()>
Public Function ToXml(Of T)(array As IEnumerable(Of T)) As XElement
   Return XElement.Parse(
           String.Format("<doc>{0}</doc>", String.Join("", array.Select(Function(s) String.Concat("<d>", s.ToString(), "</d>")))), LoadOptions.None)
 End Function

This is the sql Stored proc, shortened, not complete!

CREATE PROCEDURE [dbo].[myproc] (@blah xml)
AS ... WHERE SomeID IN (SELECT doc.t.value('.','int') from @netwerkids.nodes(N'/doc/d') as doc(t))

ReportViewer Client Print Control "Unable to load client print control"?

I have had the same problem (on several different servers). Applying SP3 and Report Viewer SP1 has helped on some of the servers, allowing the client machines to connect and download the control with no problem. However, I have had one server that, even after applying the updates, when accessing the report viewer using a client machine, it was still giving me the error. On looking into the exact URL GET request that is being sent, I discovered that it is possible to force the client machine to connect directly to the Report Server to download the control.

The user would need to enter the following url:

http://reportservername/Reports/Reserved.ReportViewerWebControl.axd?ReportSession=51bjqv45xydgos2wghu5ceza&ControlID=7617dedbf0234f89b80cad8e64431014&Culture=2057&UICulture=9&ReportStack=1&OpType=PrintHtml

This should then pop up the required download/install prompt.

Best way to log POST data in Apache?

An easier option may be to log the POST data before it gets to the server. For web applications, I use Burp Proxy and set Firefox to use it as an HTTP/S proxy, and then I can watch (and mangle) data 'on the wire' in real time.

For making API requests without a browser, SoapUI is very useful and may show similar info. I would bet that you could probably configure SoapUI to connect through Burp as well (just a guess though).

Batch program to to check if process exists

Try this:

@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause

sql query distinct with Row_Number

How about something like

;WITH DistinctVals AS (
        SELECT  distinct id 
        FROM    table 
        where   fid = 64
    )
SELECT  id,
        ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
FROM    DistinctVals

SQL Fiddle DEMO

You could also try

SELECT distinct id, DENSE_RANK() OVER (ORDER BY  id) AS RowNum
FROM @mytable
where fid = 64

SQL Fiddle DEMO

How do I declare an array of undefined or no initial size?

One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)

Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).

I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).

How should I make my VBA code compatible with 64-bit Windows?

Office 2007 is 32 bit only so there is no issue there. Your problems arise only with Office 64 bit which has both 32 and 64 bit versions.

You cannot hope to support users with 64 bit Office 2010 when you only have Office 2007. The solution is to upgrade.

If the only Declare that you have is that ShellExecute then you won't have much to do once you get hold of 64 bit Office, but it's not really viable to support users when you can't run the program that you ship! Just think what you would do you do when they report a bug?

How to convert Rows to Columns in Oracle?

 select * FROM doc_tab
    PIVOT
    (
    Min(document_id)
    FOR document_type IN ('Voters ID','Pan card','Drivers licence')
    ) 

outputs as this

enter image description here

sql fiddle demo here

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

How do I install command line MySQL client on mac?

Using MacPorts you can install the client with:

sudo port install mysql57

You also need to select the installed version as your mysql

sudo port select mysql mysql57

The server is only installed if you append -server to the package name (e.g. mysql57-server)

How to count frequency of characters in a string?

We can use frequency method of Collections class for this. Split the string into string array. Use HashSet to remove duplicates and check frequency of each object in HashSet using frequency method of Collections

void usingCollections(){

  String input = "cuttack";

  String [] stringArray = input.split("");

  Set<String> s = new HashSet(Arrays.asList(stringArray));

  for(String abc : s){

    System.out.println (abc + ":"+Collections.frequency(Arrays.asList(stringArray),abc));

  }
}

Remove quotes from String in Python

The easiest way is:

s = '"sajdkasjdsaasdasdasds"' 
import json
s = json.loads(s)

How to use subList()

Using subList(30, 38); will fail because max index 38 is not available in list, so its not possible.

Only way may be before asking for the sublist, you explicitly determine the max index using list size() method.

for example, check size, which returns 35, so call sublist(30, size());

OR

COPIED FROM pb2q comment

dataList = dataList.subList(30, 38 > dataList.size() ? dataList.size() : 38);

Java Class.cast() vs. cast operator

I've only ever used Class.cast(Object) to avoid warnings in "generics land". I often see methods doing things like this:

@SuppressWarnings("unchecked")
<T> T doSomething() {
    Object o;
    // snip
    return (T) o;
}

It's often best to replace it by:

<T> T doSomething(Class<T> cls) {
    Object o;
    // snip
    return cls.cast(o);
}

That's the only use case for Class.cast(Object) I've ever come across.

Regarding compiler warnings: I suspect that Class.cast(Object) isn't special to the compiler. It could be optimized when used statically (i.e. Foo.class.cast(o) rather than cls.cast(o)) but I've never seen anybody using it - which makes the effort of building this optimization into the compiler somewhat worthless.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Created a base class based on @sky-dev implementation. So this can be easily applied to multiple contexts, and entities.

public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
    public BaseDbContext(string connectionString)
        : base(connectionString)
    {
    }
    public override int SaveChanges()
    {

        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries<TEntity>())
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

Usage:

public class MyContext: BaseDbContext<MyEntities>
{

    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    public MyContext()
        : base("name=MyConnectionString")
    {
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    public MyContext(string connectionString)
        : base(connectionString)
    {
    }

     //DBcontext class body here (methods, overrides, etc.)
 }

How do I set up Vim autoindentation properly for editing Python files?

Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

In vim type

:help vimrc

and check your path to the _vimrc/.vimrc file with

:echo $HOME

:echo $VIM

Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

:help source

Know relationships between all the tables of database in SQL Server

Just another way to retrieve the same data using INFORMATION_SCHEMA

The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

sqlauthority way

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Just restart your wamp server and then run php bin/magento cache:clean

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

Serializing a list to JSON

building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

or this call to process

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

Setting PayPal return URL and making it auto return?

I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!

Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:

input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"

where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!

Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.

Comments please??

How to delete multiple rows in SQL where id = (x to y)

CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]       
@CODE XML
,@ERRFLAG  CHAR(1) = '0' OUTPUT    

AS        

SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  

DELETE tb_SampleTest
    WHERE 
        CODE IN(
            SELECT Item.value('.', 'VARCHAR(20)')
            FROM  @CODE.nodes('RecordList/ID') AS x(Item)
            )

IF @@ROWCOUNT = 0
    SET @ERRFLAG = 200

SET NOCOUNT OFF

Get string value delete

<RecordList>
    <ID>1</ID>
    <ID>2</ID>
</RecordList>

How can I disable a tab inside a TabControl?

I could not find an appropriate answer to the question. There looks to be no solution to disable the specific tab. What I did is to pass the specific tab to a variable and in SelectedIndexChanged event put it back to SelectedIndex:

//variable for your specific tab 
int _TAB = 0;

//here you specify your tab that you want to expose
_TAB = 1;
tabHolder.SelectedIndex = _TAB;

private void tabHolder_SelectedIndexChanged(object sender, EventArgs e)
{
    if (_TAB != 0) tabHolder.SelectedIndex = _TAB;
}

So, you don't actually disable the tab, but when another tab is clicked it always returns you to the selected tab.

How to get a URL parameter in Express?

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Query parameter

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

This worked for me on Windows 10 and powershell 5.1:

  • right click on the .ps1 file
  • Open with...
  • Choose another app
  • Copy the location of powershell.exe to the address bar (by default it won't show windows folder) i.e. C:\Windows\System32\WindowsPowerShell\v1.0
  • select powershell.exe
  • select "Always use this app to open .ps1 files"
  • click OK

De-obfuscate Javascript code to make it readable again

I have tried both of online jsbeautifier(jsbeautifier, jsnice), these tools gave me beautiful js code,

but couldn't copy for very large js (must be bug, when i copy, copied buffer contains only one character '-').

I found that only working solution was prettyjs:

http://www.thaoh.net/prettyjs/

Truncate with condition

The short answer is no: MySQL does not allow you to add a WHERE clause to the TRUNCATE statement. Here's MySQL's documentation about the TRUNCATE statement.

But the good news is that you can (somewhat) work around this limitation.

Simple, safe, clean but slow solution using DELETE

First of all, if the table is small enough, simply use the DELETE statement (it had to be mentioned):

1. LOCK TABLE my_table WRITE;
2. DELETE FROM my_table WHERE my_date<DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. UNLOCK TABLES;

The LOCK and UNLOCK statements are not compulsory, but they will speed things up and avoid potential deadlocks.

Unfortunately, this will be very slow if your table is large... and since you are considering using the TRUNCATE statement, I suppose it's because your table is large.

So here's one way to solve your problem using the TRUNCATE statement:

Simple, fast, but unsafe solution using TRUNCATE

1. CREATE TABLE my_table_backup AS
      SELECT * FROM my_table WHERE my_date>=DATE_SUB(NOW(), INTERVAL 1 MONTH);
2. TRUNCATE my_table;
3. LOCK TABLE my_table WRITE, my_table_backup WRITE;
4. INSERT INTO my_table SELECT * FROM my_table_backup;
5. UNLOCK TABLES;
6. DROP TABLE my_table_backup;

Unfortunately, this solution is a bit unsafe if other processes are inserting records in the table at the same time:

  • any record inserted between steps 1 and 2 will be lost
  • the TRUNCATE statement resets the AUTO-INCREMENT counter to zero. So any record inserted between steps 2 and 3 will have an ID that will be lower than older IDs and that might even conflict with IDs inserted at step 4 (note that the AUTO-INCREMENT counter will be back to it's proper value after step 4).

Unfortunately, it is not possible to lock the table and truncate it. But we can (somehow) work around that limitation using RENAME.

Half-simple, fast, safe but noisy solution using TRUNCATE

1. RENAME TABLE my_table TO my_table_work;
2. CREATE TABLE my_table_backup AS
     SELECT * FROM my_table_work WHERE my_date>DATE_SUB(NOW(), INTERVAL 1 MONTH);
3. TRUNCATE my_table_work;
4. LOCK TABLE my_table_work WRITE, my_table_backup WRITE;
5. INSERT INTO my_table_work SELECT * FROM my_table_backup;
6. UNLOCK TABLES;
7. RENAME TABLE my_table_work TO my_table;
8. DROP TABLE my_table_backup;

This should be completely safe and quite fast. The only problem is that other processes will see table my_table disappear for a few seconds. This might lead to errors being displayed in logs everywhere. So it's a safe solution, but it's "noisy".

Disclaimer: I am not a MySQL expert, so these solutions might actually be crappy. The only guarantee I can offer is that they work fine for me. If some expert can comment on these solutions, I would be grateful.

Prevent overwriting a file using cmd if exist

I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...

CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"

two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...

start \\filer\repo\lab\"software"\"myapp"\setup.exe

the start code here, can be set up like that, but the correct syntax is

start "\\filter\repo\lab\software\myapp\" setup.exe

This will run: setup.exe, located in: \filter\repo\lab...etc.\

How to query between two dates using Laravel and Eloquent?

I know this might be an old question but I just found myself in a situation where I had to implement this feature in a Laravel 5.7 app. Below is what worked from me.

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

You will also need to use Carbon

use Carbon\Carbon;

Is PowerShell ready to replace my Cygwin shell on Windows?

In a couple of lines, Cygwin and PowerShell are different tools however if you have Cygwin installed you can run the Cygwin executables within a PowerShell session. I've gotten so used to PowerShell that now I no longer use grep, sort, awk, etc. There are pretty much built-in alternatives in PowerShell, and if not you can find a cmdlet out there.

The main tool I find myself using is ssh.exe, but within a PowerShell session.

It works great.

What is the difference between docker-compose ports vs expose

ports:

  1. Activates the container to listen for specified port(s) from the world outside of the docker(can be same host machine or a different machine) AND also accessible world inside docker.
  2. More than one port can be specified (that's is why ports not port)

enter image description here

expose:

  1. Activates container to listen for a specific port only from the world inside of docker AND not accessible world outside of the docker.
  2. More than one port can be specified

enter image description here

How can I check the syntax of Python script without executing it?

Thanks to the above answers @Rosh Oxymoron. I improved the script to scan all files in a dir that are python files. So for us lazy folks just give it the directory and it will scan all the files in that directory that are python.

import sys
import glob, os

os.chdir(sys.argv[1])
for file in glob.glob("*.py"):
    source = open(file, 'r').read() + '\n'
    compile(source, file, 'exec')

Save this as checker.py and run python checker.py ~/YOURDirectoryTOCHECK

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

Add a linebreak in an HTML text area

In a text area, as in the form input, then just a normal line break will work:

<textarea>
This is a text area
line breaks are automatic
</textarea>

If you're talking about normal text on the page, the <br /> (or just <br> if using plain 'ole HTML4) is a line break.

However, I'd say that you often don't actually want a line break. Usually, your text is seperated into paragraphs:

<p>
  This is some text
</p>
<p>
  This is some more
</p>

Which is much better because it gives a clue as to how your text is structured to machines that read it. Machines that read it include screen readers for the partially sighted or blind, seperating text into paragraphs gives it a chance of being presented correctly to these users.

I would like to see a hash_map example in C++

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;

int main() {
    unordered_map <string, int> m;
    m["foo"] = 42;
    cout << m["foo"] << endl;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

g++ -std=c++0x main.cpp

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Instagram API: How to get all user media?

See http://instagram.com/developer/endpoints/ for information on pagination. You need to subsequentially step through the result pages, each time requesting the next part with the next_url that the result specifies in the pagination object.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

To set flashdata you need to redirect controller function

$this->session->set_flashdata('message_name', 'This is test message');

//redirect to some function
redirect("controller/function_name");

//echo in view or controller
$this->session->flashdata('message_name');

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

Basically JAVA_HOME is use to set path of the java . it is use in windows. it's used for set path of the multiple software like as java EE , ANT and Maven. this is the steps to solve your problem:

only for core java to set path : path :"C:\Program Files\Java\jre1.8.0_77\bin" but when you are use multi built like as ANT , core java then you are used JAVE_HOME in environment .

follow the steps :

JAVA_HOME:"C:\Program Files\Java\jre1.8.0_77\bin" ANT_HOME:"C:\ant\apache-ant-1.9.6"

Path: JAVA_HOME, ANT_HOME; it is the systematic way to set the environment variable..

C# removing items from listbox

With this code you can remove every item from your listbox ... Notice that you should write this code in the click event of your button :

        if (listBox1.SelectedIndex != -1)
        {
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        } 

Converting float to char*

char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);

if (ret < 0) {
    return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
    /* Result was truncated - resize the buffer and retry.
}

That will store the string representation of myFloat in myCharPointer. Make sure that the string is large enough to hold it, though.

snprintf is a better option than sprintf as it guarantees it will never write past the size of the buffer you supply in argument 2.

Pip - Fatal error in launcher: Unable to create process using '"'

Usually this is due to python version set on your Environment Variables. Check PATH (or Path) for both System and Client variables.

If its pointing to "path/to/python-installation/Python3.x-32", change it to "path/to/python-installation/Python3.x"

Again check value on both System and Client Environment Variables

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

<configuration>
 <location path="Path/To/Public/Folder">
  <system.web>
     <authorization>
        <allow users="?"/>
     </authorization>
  </system.web>
 </location>
</configuration>

Change user-agent for Selenium web-driver

To build on JJC's helpful answer that builds on Louis's helpful answer...

With PhantomJS 2.1.1-windows this line works:

driver.execute_script("return navigator.userAgent")

If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):

from selenium import webdriver
import json
from fake_useragent import UserAgent

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])

How can I make a TextBox be a "password box" and display stars when using MVVM?

Send the passwordbox control as a parameter to your login command.

<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>

Then you can call CType(parameter, PasswordBox).Password in your viewmodel.

Get clicked item and its position in RecyclerView

//Create below methods into the Activity which contains RecyclerView.


private void createRecyclerView() {

final RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    MyAdapter myAdapter=new MyAdapter(dataAray,MianActivity.this);
    recyclerView.setAdapter(myAdapter);
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    setRecyclerViewClickListner(recyclerView);
}

private void setRecyclerViewClickListner(RecyclerView recyclerView){

    final GestureDetector gestureDetector = new GestureDetector(MainActivity.this,new GestureDetector.SimpleOnGestureListener() {
        @Override public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });


    recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child =recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());
            if(child!=null && gestureDetector.onTouchEvent(motionEvent)){
               int position=recyclerView.getChildLayoutPosition(child);
                String name=itemArray.get(position).name;

            return true;
        }

        @Override
        public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean b) {

        }
    });
}

DevTools failed to load SourceMap: Could not load content for chrome-extension

I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (EDIT: this fix seems to massively speed up the browser too) was by adding a dead file

  1. physically create the file it wants\ where it wants, as a blank file (EG: "popper.min.js.map")

  2. put this in the blank file

    {
     "version": 1,
     "mappings": "",
     "sources": [],
     "names": [],
     "file": "popper.min.js"
    }
    
  3. make sure that "file": "*******" in the content of the blank file MATCHES the name of your file ******.map (minus the word ".map")

(EDIT: I suspect you could physically add this dead file method to the addon yourself)

How to use CSS to surround a number with a circle?

The problem with most of the other answers here is you need to tweak the size of the outer container so that it is the perfect size based on the font size and number of characters to be displayed. If you are mixing 1 digit numbers and 4 digit numbers, it won't work. If the ratio between the font size and the circle size isn't perfect, you'll either end up with an oval or a small number vertically aligned at the top of a large circle. This should work fine for any amount of text and any size circle. Just set the width and line-height to the same value:

_x000D_
_x000D_
.numberCircle {_x000D_
    width: 120px;_x000D_
    line-height: 120px;_x000D_
    border-radius: 50%;_x000D_
    text-align: center;_x000D_
    font-size: 32px;_x000D_
    border: 2px solid #666;_x000D_
}
_x000D_
<div class="numberCircle">1</div>_x000D_
<div class="numberCircle">100</div>_x000D_
<div class="numberCircle">10000</div>_x000D_
<div class="numberCircle">1000000</div>
_x000D_
_x000D_
_x000D_

If you need to make the content longer or shorter, all you need to do is adjust the width of the container for a better fit.

See it on JSFiddle.