Programs & Examples On #Hyperion

Hyperion is a set of performance management applications purchased by Oracle in 2007.

Git: Could not resolve host github.com error while cloning remote repository in git

One reason for this issue could be wrong/empty /etc/resolv.conf file.

The way I resolved this issue in my centos 7 minimal is as follows: my /etc/resolv.conf was empty and I added the following lines:

nameserver 192.168.1.1
nameserver 0.0.0.0

where 192.168.1.1 is my gateway, in your case it can be different.

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

Benefits of inline functions in C++?

I'd like to add that inline functions are crucial when you are building shared library. Without marking function inline, it will be exported into the library in the binary form. It will be also present in the symbols table, if exported. On the other side, inlined functions are not exported, neither to the library binaries nor to the symbols table.

It may be critical when library is intended to be loaded at runtime. It may also hit binary-compatible-aware libraries. In such cases don't use inline.

FULL OUTER JOIN vs. FULL JOIN

It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)

This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.

In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.

Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.

Can someone explain how to implement the jQuery File Upload plugin?

Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

C# Wait until condition is true

At least you can change your loop from a busy-wait to a slow poll. For example:

    while (!isExcelInteractive())
    {
        Console.WriteLine("Excel is busy");
        await Task.Delay(25);
    }

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Unix ls command: show full path when using options

You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.

ls -lart `find . -type f -name "*" `

How to iterate through a list of objects in C++

if you add an #include <algorithm> then you can use the for_each function and a lambda function like so:

for_each(data.begin(), data.end(), [](Student *it) 
{
    std::cout<<it->name;
});

you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm

and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019

How to get distinct values for non-key column fields in Laravel?

You should use groupby. In Query Builder you can do it this way:

$users = DB::table('users')
            ->select('id','name', 'email')
            ->groupBy('name')
            ->get();

Displaying the Error Messages in Laravel after being Redirected from controller

This is also good way to accomplish task.

@if($errors->any())
  {!! implode('', $errors->all('<div class="alert alert-danger">:message</div>')) !!}
@endif

We can format tag as per requirements.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

I see this topic, but in my case I was looking for a way to improve the format. Using UFormat and adding -1 day

(get-date (get-date).addDays(-1) -UFormat "%Y%m%d-%H%M")

Effective swapping of elements of an array in Java

Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the functon static final).

Declare an empty two-dimensional array in Javascript?

You can just declare a regular array like so:

var arry = [];

Then when you have a pair of values to add to the array, all you need to do is:

arry.push([value_1, value2]);

And yes, the first time you call arry.push, the pair of values will be placed at index 0.

From the nodejs repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Of course, since javascript is dynamically typed, there will be no type checker enforcing that the array remains 2 dimensional. You will have to make sure to only add pairs of coordinates and not do the following:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]

Angular window resize event

This is not exactly answer for the question but it can help somebody who needs to detect size changes on any element.

I have created a library that adds resized event to any element - Angular Resize Event.

It internally uses ResizeSensor from CSS Element Queries.

Example usage

HTML

<div (resized)="onResized($event)"></div>

TypeScript

@Component({...})
class MyComponent {
  width: number;
  height: number;

  onResized(event: ResizedEvent): void {
    this.width = event.newWidth;
    this.height = event.newHeight;
  }
}

How to disable Google Chrome auto update?

many unstable solutions I prefer to edit the host file

/etc/hosts

127.0.0.1 dl.google.com
127.0.0.1 tools.google.com

Is it possible to preview stash contents in git?

Beyond the gitk recommendation in Is it possible to preview stash contents in git? you can install tig and call tig stash. This free/open console program also allows you to choose which stash to compare

Project has no default.properties file! Edit the project properties to set one

I got the default.properties error because the Android SDK wasn't installed on the machine I was using. What happened in my case was that I was setting up a second machine to development on.

After installing the SDK, the project imported just fine. You don't have to do New Project.

Substring in excel

What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.

Send response to all clients except sender

Here is my list (updated for 1.0):

// sending to sender-client only
socket.emit('message', "this is a test");

// sending to all clients, include sender
io.emit('message', "this is a test");

// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");

// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');

// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');

// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');

// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');

// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');

// list socketid
for (var socketid in io.sockets.sockets) {}
 OR
Object.keys(io.sockets.sockets).forEach((socketid) => {});

XML Serialize generic list of serializable objects

The easiest way to do it, that I have found.. Apply the System.Xml.Serialization.XmlArray attribute to it.

[System.Xml.Serialization.XmlArray] //This is the part that makes it work
List<object> serializableList = new List<object>();

XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());

serializableList.Add(PersonList);

using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xmlSerializer.Serialize(streamWriter, serializableList);
}

The serializer will pick up on it being an array and serialize the list's items as child nodes.

Why is semicolon allowed in this python snippet?

It's allowed because authors decided to allow it: https://docs.python.org/2/reference/simple_stmts.html

If move to question why authors decided todo so, I guess it's so because semi-column is allowed as simple statement termination at least in the following langages: C++, C, C#, R, Matlab,Perl,...

So it's faster to move into usage of Python for people with background in other language. And there are no lose of generality in such deicison.

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Remove the starting slash ('\') in the second parameter (path2) of Path.Combine.

Pandas read_csv from url

As I commented you need to use a StringIO object and decode i.e c=pd.read_csv(io.StringIO(s.decode("utf-8"))) if using requests, you need to decode as .content returns bytes if you used .text you would just need to pass s as is s = requests.get(url).text c = pd.read_csv(StringIO(s)).

A simpler approach is to pass the correct url of the raw data directly to read_csv, you don't have to pass a file like object, you can pass a url so you don't need requests at all:

c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")

print(c)

Output:

                              Country         Region
0                             Algeria         AFRICA
1                              Angola         AFRICA
2                               Benin         AFRICA
3                            Botswana         AFRICA
4                             Burkina         AFRICA
5                             Burundi         AFRICA
6                            Cameroon         AFRICA
..................................

From the docs:

filepath_or_buffer :

string or file handle / StringIO The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv

The application may be doing too much work on its main thread

taken from : Android UI : Fixing skipped frames

Anyone who begins developing android application sees this message on logcat “Choreographer(abc): Skipped xx frames! The application may be doing too much work on its main thread.” So what does it actually means, why should you be concerned and how to solve it.

What this means is that your code is taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application or DB access or any other thing which causes the thread to stop for a while.

Here is a more detailed explanation:

Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.

Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.

Since Choreographer is told about every vsync events, I can tell if one of the Runnables passed along by the Choreographer.post* apis doesnt finish in one frame’s time, causing frames to be skipped.

In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.

The message “The application may be doing too much work on its main thread.” could be misleading.

source : Meaning of Choreographer messages in Logcat

Why you should be concerned

When this message pops up on android emulator and the number of frames skipped are fairly small (<100) then you can take a safe bet of the emulator being slow – which happens almost all the times. But if the number of frames skipped and large and in the order of 300+ then there can be some serious trouble with your code. Android devices come in a vast array of hardware unlike ios and windows devices. The RAM and CPU varies and if you want a reasonable performance and user experience on all the devices then you need to fix this thing. When frames are skipped the UI is slow and laggy, which is not a desirable user experience.

How to fix it

Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread

Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.

So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.

So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

Where is virtualenvwrapper.sh after pip install?

Although this is an OS X question, here's what worked for me on Linux (Red Hat).

My virtualwrapper.sh was in

~/.local/bin/virtualenvwrapper.sh

This is probably because I installed virtualenvwrapper locally, using the --user flag...

pip install --user virtualenvwrapper

...as an alternative to the risky practice of using sudo pip.

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

First of all, run your IDE as Admin. After that, right click the project folder -> Project Facets and make sure that the Java Version is set correct. On my PC. (For Example 1.8) Now it should work.

Don't just start your server, for example Wildfly, using the cmd. It has to be launched within the IDE and now visit your localhost URL. Example: http://localhost:8080/HelloWorldServlet/HelloWorld

How to have jQuery restrict file types on upload?

You can get the value of a file field just the same as any other field. You can't alter it, however.

So to superficially check if a file has the right extension, you could do something like this:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}

Using Python Requests: Sessions, Cookies, and POST

I don't know how stubhub's api works, but generally it should look like this:

s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)

Now your session contains cookies provided by login form. To access cookies of this session simply use

s.cookies

Any further actions like another requests will have this cookie

Replacing objects in array

function getMatch(elem) {
    function action(ele, val) {
        if(ele === val){ 
            elem = arr2[i]; 
        }
    }

    for (var i = 0; i < arr2.length; i++) {
        action(elem.id, Object.values(arr2[i])[0]);
    }
    return elem;
}

var modified = arr1.map(getMatch);

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

How to import XML file into MySQL database table using XML_LOAD(); function

you can specify fields like this:

LOAD XML LOCAL INFILE '/pathtofile/file.xml' 
INTO TABLE my_tablename(personal_number, firstname, ...); 

Difference between null and empty ("") Java String

null means the name isn't referencing any instantiated object. "" means an empty string.

Here a is referencing some object which happens to be an empty string. b isn't referencing any object as it's null.

How to remove border of drop down list : CSS

select#xyz {
  border:0px;
  outline:0px;
}

Exact solution.

Copy map values to vector in STL

Using lambdas one can perform the following:

{
   std::map<std::string,int> m;
   std::vector<int> v;
   v.reserve(m.size());
   std::for_each(m.begin(),m.end(),
                 [&v](const std::map<std::string,int>::value_type& p) 
                 { v.push_back(p.second); });
}

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  <style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
     }
    });

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

return isFormValid;
}   
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>

Git/GitHub can't push to master

The below cmnds will fix the issue.

 git pull --rebase
 git push

How can you customize the numbers in an ordered list?

Stole a lot of this from other answers, but this is working in FF3 for me. It has upper-roman, uniform indenting, a close bracket.

<!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>
<title> new document </title>
<style type="text/css">
<!--
ol {
  counter-reset: item;
  margin-left: 0;
  padding-left: 0;
}
li {
  margin-bottom: .5em;
}
li:before {
  display: inline-block;
  content: counter(item, upper-roman) ")";
  counter-increment: item;
  width: 3em;
}
-->
</style>
</head>

<body>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li>Six</li>
  <li>Seven</li>
  <li>Eight</li>
  <li>Nine</li>
  <li>Ten</li>
</ol>
</body>
</html>

What is Mocking?

Other answers explain what mocking is. Let me walk you through it with different examples. And believe me, it's actually far more simpler than you think.

tl;dr It's an instance of the original class. It has other data injected into so you avoid testing the injected parts and solely focus on testing the implementation details of your class/functions.

Simple example:

class Foo {
    func add (num1: Int, num2: Int) -> Int { // Line A 
        return num1 + num2 // Line B
    }
}

let unit = Foo() // unit under test
assertEqual(unit.add(1,5),6)

As you can see, I'm not testing LineA ie I'm not validating the input parameters. I'm not validating to see if num1, num2 are an Integer. I have no asserts against that.

I'm only testing to see if LineB (my implementation) given the mocked values 1 and 5 is doing as I expect.

Obviously in the real word this can become much more complex. The parameters can be a custom object like a Person, Address, or the implementation details can be more than a single +. But the logic of testing would be the same.

Non-coding Example:

Assume you're building a machine that identifies the type and brand name of electronic devices for an airport security. The machine does this by processing what it sees with its camera.

Now your manager walks in the door and asks you to unit-test it.

Then you as a developer you can either bring 1000 real objects, like a MacBook pro, Google Nexus, a banana, an iPad etc in front of it and test and see if it all works.

But you can also use mocked objects, like an identical looking MacBook pro (with no real internal parts) or a plastic banana in front of it. You can save yourself from investing in 1000 real laptops and rotting bananas.

The point is you're not trying to test if the banana is fake or not. Nor testing if the laptop is fake or not. All you're doing is testing if your machine once it sees a banana it would say not an electronic device and for a MacBook Pro it would say: Laptop, Apple. To the machine, the outcome of its detection should be the same for fake/mocked electronics and real electronics. If your machine also factored in the internals of a laptop (x-ray scan) or banana then your mocks' internals need to look the same as well. But you could also use a gadget with a friend motherboard. Had your machine tested whether or not devices can power on then well you'd need real devices.

The logic mentioned above applies to unit-testing of actual code as well. That is a function should work the same with real values you get from real input (and interactions) or mocked values you inject during unit-testing. And just as how you save yourself from using a real banana or MacBook, with unit-tests (and mocking) you save yourself from having to do something that causes your server to return a status code of 500, 403, 200, etc (forcing your server to trigger 500 is only when server is down, while 200 is when server is up. It gets difficult to run 100 network focused tests if you have to constantly wait 10 seconds between switching over server up and down). So instead you inject/mock a response with status code 500, 200, 403, etc and test your unit/function with a injected/mocked value.

Be aware:

Sometimes you don't correctly mock the actual object. Or you don't mock every possibility. E.g. your fake laptops are dark, and your machine accurately works with them, but then it doesn't work accurately with white fake laptops. Later when you ship this machine to customers they complain that it doesn't work all the time. You get random reports that it's not working. It takes you 3 months of time to finally figure out that the color of fake laptops need to be more varied so you can test your modules appropriately.

For a true coding example, your implementation may be different for status code 200 with image data returned vs 200 with image data not returned. For this reason it's good to use an IDE that provides code coverage e.g. the image below shows that your unit-tests don't ever go through the lines marked with brown.

enter image description here

image source

Real world coding Example:

Let's say you are writing an iOS application and have network calls.Your job is to test your application. To test/identify whether or not the network calls work as expected is NOT YOUR RESPONSIBILITY . It's another party's (server team) responsibility to test it. You must remove this (network) dependency and yet continue to test all your code that works around it.

A network call can return different status codes 404, 500, 200, 303, etc with a JSON response.

Your app is suppose to work for all of them (in case of errors, your app should throw its expected error). What you do with mocking is you create 'imaginary—similar to real' network responses (like a 200 code with a JSON file) and test your code without 'making the real network call and waiting for your network response'. You manually hardcode/return the network response for ALL kinds of network responses and see if your app is working as you expect. (you never assume/test a 200 with incorrect data, because that is not your responsibility, your responsibility is to test your app with a correct 200, or in case of a 400, 500, you test if your app throws the right error)

This creating imaginary—similar to real is known as mocking.

In order to do this, you can't use your original code (your original code doesn't have the pre-inserted responses, right?). You must add something to it, inject/insert that dummy data which isn't normally needed (or a part of your class).

So you create an instance the original class and add whatever (here being the network HTTPResponse, data OR in the case of failure, you pass the correct errorString, HTTPResponse) you need to it and then test the mocked class.

Long story short, mocking is to simplify and limit what you are testing and also make you feed what a class depends on. In this example you avoid testing the network calls themselves, and instead test whether or not your app works as you expect with the injected outputs/responses —— by mocking classes

Needless to say, you test each network response separately.


Now a question that I always had in my mind was: The contracts/end points and basically the JSON response of my APIs get updated constantly. How can I write unit tests which take this into consideration?

To elaborate more on this: let’s say model requires a key/field named username. You test this and your test passes. 2 weeks later backend changes the key's name to id. Your tests still passes. right? or not?

Is it the backend developer’s responsibility to update the mocks. Should it be part of our agreement that they provide updated mocks?

The answer to the above issue is that: unit tests + your development process as a client-side developer should/would catch outdated mocked response. If you ask me how? well the answer is:

Our actual app would fail (or not fail yet not have the desired behavior) without using updated APIs...hence if that fails...we will make changes on our development code. Which again leads to our tests failing....which we’ll have to correct it. (Actually if we are to do the TDD process correctly we are to not write any code about the field unless we write the test for it...and see it fail and then go and write the actual development code for it.)

This all means that backend doesn’t have to say: “hey we updated the mocks”...it eventually happens through your code development/debugging. ??Because it’s all part of the development process! Though if backend provides the mocked response for you then it's easier.

My whole point on this is that (if you can’t automate getting updated mocked API response then) some human interaction is required ie manual updates of JSONs and having short meetings to make sure their values are up to date will become part of your process

This section was written thanks to a slack discussion in our CocoaHead meetup group


For iOS devs only:

A very good example of mocking is this Practical Protocol-Oriented talk by Natasha Muraschev. Just skip to minute 18:30, though the slides may become out of sync with the actual video ???

I really like this part from the transcript:

Because this is testing...we do want to make sure that the get function from the Gettable is called, because it can return and the function could theoretically assign an array of food items from anywhere. We need to make sure that it is called;

How to change Android usb connect mode to charge only?

To change the connect mode selection try Settings -> Wireless & Networks -> USB Connection. You can shoose to Charging, Mass Storage, Tethered, and ask on connection.

How to debug a Flask app

with virtual env activate

export FLASK_DEBUG=true

you can configure

export FLASK_APP=app.py  # run.py
export FLASK_ENV = "development"

to start

flask run

the result

 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: xxx-xxx-xxx

and if you change

export FLASK_DEBUG=false

 * Environment: development
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

How can I get the max (or min) value in a vector?

If you want to use the function std::max_element(), the way you have to do it is:

double max = *max_element(vector.begin(), vector.end());
cout<<"Max value: "<<max<<endl;

I hope this can help.

How to draw rounded rectangle in Android UI?

<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:padding="10dp"
  android:shape="rectangle">
    <solid android:color="@color/colorAccent" /> 
    <corners
      android:bottomLeftRadius="500dp"
      android:bottomRightRadius="500dp"
      android:topLeftRadius="500dp"
      android:topRightRadius="500dp" />
</shape>

Now, in which element you want to use this shape just add: android:background="@drawable/custom_round_ui_shape"

Create a new XML in drawable named "custom_round_ui_shape"

System.currentTimeMillis vs System.nanoTime

one thing here is the inconsistency of the nanoTime method.it does not give very consistent values for the same input.currentTimeMillis does much better in terms of performance and consistency,and also ,though not as precise as nanoTime,has a lower margin of error,and therefore more accuracy in its value. i would therefore suggest that you use currentTimeMillis

How can I find a specific file from a Linux terminal?

Try this (via a shell):

update db
locate index.html

Or:

find /var -iname "index.html"

Replace /var with your best guess as to the directory it is in but avoid starting from /

How can I get the timezone name in JavaScript?

This gets the timezone code (e.g., GMT) in older javascript (I'm using google app script with old engine):

function getTimezoneName() {
  return new Date().toString().get(/\((.+)\)/);
}

I'm just putting this here in case someone needs it.

What are the aspect ratios for all Android phone and tablet devices?

The Sony Tablet P is old, but it can switch between 32:15 and 32:30 for each app in landscape mode, and vice-versa in portrait mode, so that's a minimum range to aim for

How to make a HTTP request using Ruby on Rails?

require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')

How to log a method's execution time exactly in milliseconds?

I use this:

clock_t start, end;
double elapsed;
start = clock();

//Start code to time

//End code to time

end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
NSLog(@"Time: %f",elapsed);

But I'm not sure about CLOCKS_PER_SEC on the iPhone. You might want to leave it off.

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

How to get distinct results in hibernate with joins and row-based limiting (paging)?

I will now explain a different solution, where you can use the normal query and pagination method without having the problem of possibly duplicates or suppressed items.

This Solution has the advance that it is:

  • faster than the PK id solution mentioned in this article
  • preserves the Ordering and don’t use the 'in clause' on a possibly large Dataset of PK’s

The complete Article can be found on my blog

Hibernate gives the possibility to define the association fetching method not only at design time but also at runtime by a query execution. So we use this aproach in conjunction with a simple relfection stuff and can also automate the process of changing the query property fetching algorithm only for collection properties.

First we create a method which resolves all collection properties from the Entity Class:

public static List<String> resolveCollectionProperties(Class<?> type) {
  List<String> ret = new ArrayList<String>();
  try {
   BeanInfo beanInfo = Introspector.getBeanInfo(type);
   for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
     if (Collection.class.isAssignableFrom(pd.getPropertyType()))
     ret.add(pd.getName());
   }
  } catch (IntrospectionException e) {
    e.printStackTrace();
  }
  return ret;
}

After doing that you can use this little helper method do advise your criteria object to change the FetchMode to SELECT on that query.

Criteria criteria = …

//    … add your expression here  …

// set fetchmode for every Collection Property to SELECT
for (String property : ReflectUtil.resolveCollectionProperties(YourEntity.class)) {
  criteria.setFetchMode(property, org.hibernate.FetchMode.SELECT);
}
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
criteria.list();

Doing that is different from define the FetchMode of your entities at design time. So you can use the normal join association fetching on paging algorithms in you UI, because this is most of the time not the critical part and it is more important to have your results as quick as possible.

The ResourceConfig instance does not contain any root resource classes

yes adding the init param for com.sun.jersey.config.property.packages fixed this issue for me.

was merging a jersey rest services into maven based spring application and got this error.

ASP.NET MVC Html.DropDownList SelectedValue

This is how I fixed this problem:

I had the following:

Controller:

ViewData["DealerTypes"] = Helper.SetSelectedValue(listOfValues, selectedValue) ;

View

<%=Html.DropDownList("DealerTypes", ViewData["DealerTypes"] as SelectList)%>

Changed by the following:

View

<%=Html.DropDownList("DealerTypesDD", ViewData["DealerTypes"] as SelectList)%>

It appears that the DropDown must not have the same name has the ViewData name :S weird but it worked.

CSS vertical alignment of inline/inline-block elements

For fine tuning the position of an inline-block item, use top and left:

  position: relative;
  top: 5px;
  left: 5px;

Thanks CSS-Tricks!

DATEDIFF function in Oracle

Just subtract the two dates:

select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;

The result will be the difference in days.

More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

Git: See my last commit

$ git diff --name-only HEAD^..HEAD

or

$ git log --name-only HEAD^..HEAD

how to check if a form is valid programmatically using jQuery Validation Plugin

iContribute: It's never too late for a right answer.

var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
  form.submit();
}else{
  console.log("Required field missing.");
}

This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

.autocomplete is not a function Error

I faced the same problem and try to solve, but unfortunately it wouldn't work anymore ! If you are facing the same problem and can't find the solution, it may help you.

If you configure jquery/jquery-ui globally in webpack, you need to import autocomplete like this

import { autocomplete } from 'webpack-jquery-ui';

And you must include jquery-ui.css in the head section of html, i don't understand why its not working without it!

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Hope your problem will be solved.

And make sure you include/install the following three

  1. jquery-ui-css
  2. jquery-ui
  3. jquery

How do I use this JavaScript variable in HTML?

A good place to start learning how to manipulate pages s the Mozilla Developer Network, they've got a great tutorial about the DOM.

One way you could do it is with document.write, which writes html at the end of the currently loaded part of the document - in this case, after the script tag.

<script>
  var name = prompt("What's your name?");
  document.write("<p>" + name.length + "</p>");
</script>

But it's not a very clean way of doing it. Keep document.write for testing purpose because in most cases you can't predict where it will append the content.

EDIT: Here, the "clever" way would be to do something like this:

<script type="text/javascript">
  window.addEventListener("load", function(e) {
    var name = prompt("What's your name?") || "";
    var text = document.createTextNode(name.length);
    document.getElementById("nameLength").appendChild(text);
  });
</script>
<p id="nameLength"></p>

But people are generally lazy and you'll often see .innerHTML = "something" instead of a text node.

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

How do I run a batch file from my Java Application?

ProcessBuilder is the Java 5/6 way to run external processes.

How to install SignTool.exe for Windows 10

Location:

C:\Program Files (x86)\Windows Kits\10\App Certification Kit\signtool.exe

What is "String args[]"? parameter in main method Java

In addition to all the previous comments.

public static void main(String[] args) 

can be written as

 public static void main(String...arg)

or

 public static void main(String...strings)

Conversion hex string into ascii in bash command line

The values you provided are UTF-8 values. When set, the array of:

declare -a ARR=(0xA7 0x9B 0x46 0x8D 0x1E 0x52 0xA7 0x9B 0x7B 0x31 0xD2)

Will be parsed to print the plaintext characters of each value.

for ((n=0; n < ${#ARR[*]}; n++)); do echo -e "\u${ARR[$n]//0x/}"; done

And the output will yield a few printable characters and some non-printable characters as shown here:

enter image description here

For converting hex values to plaintext using the echo command:

echo -e "\x<hex value here>"

And for converting UTF-8 values to plaintext using the echo command:

echo -e "\u<UTF-8 value here>"

And then for converting octal to plaintext using the echo command:

echo -e "\0<octal value here>"

When you have encoding values you aren't familiar with, take the time to check out the ranges in the common encoding schemes to determine what encoding a value belongs to. Then conversion from there is a snap.

Is it better to use "is" or "==" for number comparison in Python?

That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.

>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False

So you should always use == to compare numbers.

What’s the best way to get an HTTP response code from a URL?

Update using the wonderful requests library. Note we are using the HEAD request, which should happen more quickly then a full GET or POST request.

import requests
try:
    r = requests.head("https://stackoverflow.com")
    print(r.status_code)
    # prints the int of the status code. Find more at httpstatusrappers.com :)
except requests.ConnectionError:
    print("failed to connect")

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

How to fix .pch file missing on build?

Fix:

  1. Make sure you have xxxxx.cpp in your project

  2. Compile xxxxx.cpp with /Yc flag (Create Precompiled Header)
    (right click on xxxxx.cpp -> properties -> Precompiled Headers -> create)

  3. Compile all other files with /Yu flag (Use Precompiled Header)
    (right click on project -> properties -> Precompiled Headers -> use)

jQuery, simple polling example

function poll(){
    $("ajax.php", function(data){
        //do stuff  
    }); 
}

setInterval(function(){ poll(); }, 5000);

What killed my process and why?

Try:

dmesg -T| grep -E -i -B100 'killed process'

Where -B100 signifies the number of lines before the kill happened.

Omit -T on Mac OS.

Count number of occurrences for each unique value

If i am understanding your question, would this work? (you will have to replace with your actual column and table names)

SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3

MySQL Sum() multiple columns

SELECT student, (SUM(mark1)+SUM(mark2)+SUM(mark3)....+SUM(markn)) AS Total
 FROM your_table
 GROUP BY student

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

In my case artifactory was down. npm install command is throwing below error.

npm ERR! registry error parsing json

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

Limitations of SQL Server Express

You can't install Integration Services with it. Express does not support Integration Services. So if you want build say SSIS-packages you'll need at least Standard Edition.

See more here.

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot

enter image description here

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

Link to download apache http server for 64bit windows.

An unofficial 64-bit Windows build is available from Apache Lounge.

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later):

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run since DOM is loaded and ready
});

Above is the equivalent of jQuery .ready:

$(document).ready(function() {
    console.log("Ready!");
});

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.

$(function() {
    console.log("ready!");
});

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready):

DO NOT use an IIFE like this that is self executing:

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

This IIFE will NOT wait for your DOM to load. (I'm even talking about latest version of Chrome browser!)

Spring schemaLocation fails when there is no internet connection

I would like to add some additional aspect of this discussion. In windows OS I have observed that when a jar file containing schema is stored in a directory whose path contains a space character, for instance like in the following example

"c:\Program Files\myApp\spring-beans-4.0.2.RELEASE.jar"

then specifying schema location URL in the following way is not sufficient when you are developing some standalone application that should work also offline

<beans
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
    />

I have learned that result of such schema location URL resolution is a file which has a path like the following

"c:\Program%20Files\myApp\spring-beans-4.0.2.RELEASE.jar"

When I started my application from some other directory which didn't contain space character on its path then schema location resolution worked fine. Maybe somebody faced similar problems? Nevertheless I discoverd that classpath protocol works fine in my case

<beans
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
    />

How get all values in a column using PHP?

Since mysql_* are deprecated, so here is the solution using mysqli.

$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
  die("Connection to MySQL-server failed!"); 
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
   while($arr = $executingFetchQuery->fetch_assoc())
   {
        $resultArr[] = $arr['name'];//storing values into an array
   }
}
print_r($resultArr);//print the rows returned by query, containing specified columns

There is another way to do this using PDO

  $db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
  //to fetch records
  $fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
  $fetchD->execute();//executing the query
  $resultArr = array();//to store results
  while($row = $fetchD->fetch())
  {
     $resultArr[] = $row['name'];
  }
  print_r($resultArr);

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

How to create cross-domain request?

It is nothing you can do in the client side. I added @CrossOrigin in the controller in the server side and it works.

@RestController
@CrossOrigin(origins = "*")
public class MyController

Please refer to docs.

Lin

Convert int to ASCII and back in Python

>>> ord("a")
97
>>> chr(97)
'a'

MySQL create stored procedure syntax with delimiter

Getting started with stored procedure syntax in MySQL (using the terminal):

1. Open a terminal and login to mysql like this:

el@apollo:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
mysql> 

2. Take a look to see if you have any procedures:

mysql> show procedure status;
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name          | Type      | Definer | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
|   yourdb  | sp_user_login | PROCEDURE | root@%  | 2013-12-06 14:10:25 | 2013-12-06 14:10:25 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.01 sec)

I have one defined, you probably have none to start out.

3. Change to the database, delete it.

mysql> use yourdb;
Database changed

mysql> drop procedure if exists sp_user_login;
Query OK, 0 rows affected (0.01 sec)
    
mysql> show procedure status;
Empty set (0.00 sec)
    

4. Ok so now I have no stored procedures defined. Make the simplest one:

mysql> delimiter //
mysql> create procedure foobar()
    -> begin select 'hello'; end//
Query OK, 0 rows affected (0.00 sec)

The // will communicate to the terminal when you are done entering commands for the stored procedure. the stored procedure name is foobar. it takes no parameters and should return "hello".

5. See if it's there, remember to set back your delimiter!:

 mysql> show procedure status;
 -> 
 -> 

Gotcha! Why didn't this work? You set the delimiter to // remember? Set it back to ;

6. Set the delimiter back and look at the procedure:

mysql> delimiter ;
mysql> show procedure status;
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name   | Type      | Definer        | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb    | foobar | PROCEDURE | root@localhost | 2013-12-06 14:27:23 | 2013-12-06 14:27:23 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)

   

7. Run it:

mysql> call foobar();
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Hello world complete, lets overwrite it with something better.

8. Drop foobar, redefine it to accept a parameter, and re run it:

mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> show procedure status;
Empty set (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar (in var1 int)
    -> begin select var1 + 2 as result;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call foobar(5);
+--------+
| result |
+--------+
|      7 |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Nice! We made a procedure that takes input, modifies it, and does output. Now lets do an out variable.

9. Remove foobar, Make an out variable, run it:

mysql> delimiter ;
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar(out var1 varchar(100))
    -> begin set var1="kowalski, what's the status of the nuclear reactor?";
    -> end//
Query OK, 0 rows affected (0.00 sec)


mysql> delimiter ;
mysql> call foobar(@kowalski_status);
Query OK, 0 rows affected (0.00 sec)

mysql> select @kowalski_status;
+-----------------------------------------------------+
| @kowalski_status                                    |
+-----------------------------------------------------+
| kowalski, what's the status of the nuclear reactor? |
+-----------------------------------------------------+
1 row in set (0.00 sec)

10. Example of INOUT usage in MySQL:

mysql> select 'ricksays' into @msg;
Query OK, 1 row affected (0.00 sec)


mysql> delimiter //
mysql> create procedure foobar (inout msg varchar(100))
-> begin
-> set msg = concat(@msg, " never gonna let you down");
-> end//


mysql> delimiter ;


mysql> call foobar(@msg);
Query OK, 0 rows affected (0.00 sec)


mysql> select @msg;
+-----------------------------------+
| @msg                              |
+-----------------------------------+
| ricksays never gonna let you down |
+-----------------------------------+
1 row in set (0.00 sec)

Ok it worked, it joined the strings together. So you defined a variable msg, passed in that variable into stored procedure called foobar, and @msg was written to by foobar.

Now you know how to make stored procedures with delimiters. Continue this tutorial here, start in on variables within stored procedures: http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

What is stability in sorting algorithms and why is it important?

There's a few reasons why stability can be important. One is that, if two records don't need to be swapped by swapping them you can cause a memory update, a page is marked dirty, and needs to be re-written to disk (or another slow medium).

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Change Button color onClick

Using jquery, try this. if your button id is say id= clickme

$("clickme").on('çlick', function(){

$(this).css('background-color', 'grey'); .......

How to implement a binary tree?

I want to show a variation of @apadana's method, which is more useful when there is a considerable number of nodes:

'''
Suppose we have the following tree
      10
    /    \
  11      9
 /  \     / \
7   12  15   8
'''
# Step 1 - Create nodes - Use a list instead of defining each node separately
nlist = [10,11,7,9,15,8,12]; n = []
for i in range(len(nlist)): n.append(Node(nlist[i]))

# Step 2 - Set each node position
n[0].left  = n[1]
n[1].left = n[2]
n[0].right = n[3]
n[3].left = n[4]
n[3].right = n[5]
n[1].right = n[6]

Remove a file from the list that will be committed

You want to do this:

git add -u
git reset HEAD path/to/file
git commit

Be sure and do this from the top level of the repo; add -u adds changes in the current directory (recursively).

The key line tells git to reset the version of the given path in the index (the staging area for the commit) to the version from HEAD (the currently checked-out commit).

And advance warning of a gotcha for others reading this: add -u stages all modifications, but doesn't add untracked files. This is the same as what commit -a does. If you want to add untracked files too, use add . to recursively add everything.

Check for column name in a SqlDataReader object

You can also call GetSchemaTable() on your DataReader if you want the list of columns and you don't want to have to get an exception...

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Count number of lines in a git repository

I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it

So this is what I use now:

git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l

Git - how delete file from remote repository

The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again

Java Equivalent of C# async/await?

First, understand what async/await is. It is a way for a single-threaded GUI application or an efficient server to run multiple "fibers" or "co-routines" or "lightweight threads" on a single thread.

If you are ok with using ordinary threads, then the Java equivalent is ExecutorService.submit and Future.get. This will block until the task completes, and return the result. Meanwhile, other threads can do work.

If you want the benefit of something like fibers, you need support in the container (I mean in the GUI event loop or in the server HTTP request handler), or by writing your own.

For example, Servlet 3.0 offers asynchronous processing. JavaFX offers javafx.concurrent.Task. These don't have the elegance of language features, though. They work through ordinary callbacks.

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

Help with packages in java - import does not work

Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.

You do this using the -classpath argument for both javac.exe and java.exe.

Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:

java -classpath .;company.jar foo.bar.baz.YourClass

Google for "Java classpath". It'll find links like this.

One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.

SVG gradient using CSS

Here is a solution where you can add a gradient and change its colours using only CSS:

_x000D_
_x000D_
// JS is not required for the solution. It's used only for the interactive demo._x000D_
const svg = document.querySelector('svg');_x000D_
document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green'));_x000D_
document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red'));
_x000D_
svg.green stop:nth-child(1) {_x000D_
  stop-color: #60c50b;_x000D_
}_x000D_
svg.green stop:nth-child(2) {_x000D_
  stop-color: #139a26;_x000D_
}_x000D_
_x000D_
svg.red stop:nth-child(1) {_x000D_
  stop-color: #c84f31;_x000D_
}_x000D_
svg.red stop:nth-child(2) {_x000D_
  stop-color: #dA3448;_x000D_
}
_x000D_
<svg class="green" width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
  <linearGradient id="gradient">_x000D_
    <stop offset="0%" />_x000D_
    <stop offset="100%" />_x000D_
  </linearGradient>_x000D_
  <rect width="100" height="50" fill="url(#gradient)" />_x000D_
</svg>_x000D_
_x000D_
<br/>_x000D_
<button id="greenButton">Green</button>_x000D_
<button id="redButton">Red</button>
_x000D_
_x000D_
_x000D_

C# Parsing JSON array of objects

string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";

                  string jsonData = jsonData1.Replace("\"", "");


                  DataSet ds = new DataSet();
                  DataTable dt = new DataTable();
       JArray array= JArray.Parse(jsonData);

couldnot parse , if the vaule is a string..

look at name : meals , if name : 1 then it will parse

border-radius not working

To whomever may have this issue. My problem was border-collapse. It was set to:

border-collapse: collapse;

I set it to:

border-collapse: separate; 

and it fixed the issue.

Cannot start session without errors in phpMyAdmin

Problem usually lies on your browser end.

You need to flush your browser cache, delete the cookies for the server/host and then retry loading phpMyAdmin.

If you want to go all out, clear out the session folder on the server as well.

One possible reason for this is a session data mismatch between the browser and the webserver causing it to not be able to pull out the required session info and dumping this error dialogue on your lap.

Understanding the Linux oom-killer's logs

Sum of total_vm is 847170 and sum of rss is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.

Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.

rss for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss and file-rss.

[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB

Append same text to every cell in a column in Excel

Highlight the column and then Ctrl + F.

Find and replace

Find ".com"

Replace ".com, "

And then one for .in

Find and replace

Find ".in"

Replace ".in, "

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

delete 'android/app/.settings' folder

or

delete 'android/.settings' folder

or

delete 'android/.build' folder

or

delete 'android/.idea' folder

and

yarn react-native run android

Removing all line breaks and adding them after certain text

I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

angularjs getting previous route path

Use the $locationChangeStart or $locationChangeSuccess events, 3rd parameter:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('start', evt, absNewUrl, absOldUrl);
});
$scope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {
   console.log('success', evt, absNewUrl, absOldUrl);
});

Sorting Directory.GetFiles()

If you want to sort by something like creation date you probably need to use DirectoryInfo.GetFiles and then sort the resulting array using a suitable Predicate.

Java: Get month Integer from Date

tl;dr

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to wait in a batch script?

You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use

ping -n 11 127.0.0.1 > nul

This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)

How to convert timestamps to dates in Bash?

I had to convert timestamps inline in my bash history to make sense to me.

Maybe the following coming from an answer to How do I replace a substring by the output of a shell command with sed, awk or such? could be interesting to other readers too. Kudos for the original sed inline code go to @Gabriel.

cat ~/.bash_history | sed "s/^#\([0-9]\+\)$/echo -n '#'; date -u --d @\1 '\+\%Y-\%m-\%d \%T'/e" | less

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

Bash array with spaces in elements

I used to reset the IFS value and rollback when done.

# backup IFS value
O_IFS=$IFS

# reset IFS value
IFS=""

FILES=(
"2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg"
)

for file in ${FILES[@]}; do
    echo ${file}
done

# rollback IFS value
IFS=${O_IFS}

Possible output from the loop:

2011-09-04 21.43.02.jpg

2011-09-05 10.23.14.jpg

2011-09-09 12.31.16.jpg

2011-09-11 08.43.12.jpg

How to convert byte[] to InputStream?

Should be easy to find in the javadocs...

byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);

How to Flatten a Multidimensional Array?

The trick is passing the both the source and destination arrays by reference.

function flatten_array(&$arr, &$dst) {
    if(!isset($dst) || !is_array($dst)) {
        $dst = array();
    }
    if(!is_array($arr)) {
        $dst[] = $arr;
    } else {
        foreach($arr as &$subject) {
            flatten_array($subject, $dst);
        }
    }
}

$recursive = array('1', array('2','3',array('4',array('5','6')),'7',array(array(array('8'),'9'),'10')));
echo "Recursive: \r\n";
print_r($recursive);
$flat = null;
flatten_array($recursive, $flat);

echo "Flat: \r\n";
print_r($flat);

// If you change line 3 to $dst[] = &$arr; , you won't waste memory,
// since all you're doing is copying references, and imploding the array 
// into a string will be both memory efficient and fast:)

echo "String:\r\n";
echo implode(',',$flat);

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

Check for the name of the

templates

folder. it should be templates not template(without s).

How to measure elapsed time

From Java 8 onward you can try the following:

import java.time.*;
import java.time.temporal.ChronoUnit;

Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();

System.out.println(Duration.between(start_time, stop_time).toMillis());

//or

System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));

How to set "value" to input web element using selenium?

driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

What is the difference between Scala's case class and class?

The case class construct in Scala can also be seen as a convenience to remove some boilerplate.

When constructing a case class Scala gives you the following.

  • It creates a class as well as its companion object
  • Its companion object implements the apply method that you are able to use as a factory method. You get the syntactic sugar advantage of not having to use the new keyword.

Because the class is immutable you get accessors, which are just the variables (or properties) of the class but no mutators (so no ability to change the variables). The constructor parameters are automatically available to you as public read only fields. Much nicer to use than Java bean construct.

  • You also get hashCode, equals, and toString methods by default and the equals method compares an object structurally. A copy method is generated to be able to clone an object (with some fields having new values provided to the method).

The biggest advantage as has been mentioned previously is the fact that you can pattern match on case classes. The reason for this is because you get the unapply method which lets you deconstruct a case class to extract its fields.


In essence what you are getting from Scala when creating a case class (or a case object if your class takes no arguments) is a singleton object which serves the purpose as a factory and as an extractor .

What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

You can also use some existing API's like GroupDocs.Viewer which can convert your document into image or html and then you will be able to display it in your own application.

Export to xls using angularjs

When I needed something alike, ng-csv and other solutions here didn't completely help. My data was in $scope and there were no tables showing it. So, I built a directive to export given data to Excel using Sheet.js (xslsx.js) and FileSaver.js.

Here is my solution packed.

For example, the data is:

$scope.jsonToExport = [
    {
      "col1data": "1",
      "col2data": "Fight Club",
      "col3data": "Brad Pitt"
    },
    {
      "col1data": "2",
      "col2data": "Matrix Series",
      "col3data": "Keanu Reeves"
    },
    {
      "col1data": "3",
      "col2data": "V for Vendetta",
      "col3data": "Hugo Weaving"
    }
];

I had to prepare data as array of arrays for my directive in my controller:

$scope.exportData = [];
// Headers:
$scope.exportData.push(["#", "Movie", "Actor"]);
// Data:
angular.forEach($scope.jsonToExport, function(value, key) {
  $scope.exportData.push([value.col1data, value.col2data, value.col3data]);
});

Finally, add directive to my template. It shows a button. (See the fiddle).

<div excel-export export-data="exportData" file-name="{{fileName}}"></div>

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

how to install tensorflow on anaconda python 3.6

Please refer this link :

  • Go to https://www.anaconda.com/products/individual and click the “Download” -button
  • Download the Python 3.7 64-Bit (x86) Installer
  • Run the downloaded bash script (.sh) file to begin the installation. See here for more details.
  • -When prompted with the question “Do you wish the installer to prepend the Anaconda<2 or 3> install location to PATH in your /home//.bashrc ?”, answer “Yes”. If you enter “No”, you must manually add the path to Anaconda or conda will not work.

Select Windows or linked base command, In my case I have used Linux :

Create a new Anaconda virtual environment Open a new Terminal window

Type the following command: The above will create a new virtual environment with name tensorflow

conda create -n tensorflow pip python=3.8

 conda activate tensorflow

enter image description here

enter image description here

How to remove all namespaces from XML with C#?

Another solution that takes into account possibly interleaving TEXT and ELEMENT nodes, e.g.:

<parent>
    text1
    <child1/>
    text2
    <child2/>
</parent>

Code:

using System.Linq;

namespace System.Xml.Linq
{
    public static class XElementTransformExtensions
    {
        public static XElement WithoutNamespaces(this XElement source)
        {
            return new XElement(source.Name.LocalName,
                source.Attributes().Select(WithoutNamespaces),
                source.Nodes().Select(WithoutNamespaces)
            );
        }

        public static XAttribute WithoutNamespaces(this XAttribute source)
        {
            return !source.IsNamespaceDeclaration
                ? new XAttribute(source.Name.LocalName, source.Value)
                : default(XAttribute);
        }

        public static XNode WithoutNamespaces(this XNode source)
        {
            return
                source is XElement
                    ? WithoutNamespaces((XElement)source)
                    : source;
        }
    }
}

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

JAVA_HOME should point to a JDK not a JRE

Under System Variables add below

JAVA_HOME = C:\Program Files\Java\jdk1.8.0_201

JDK_HOME = %JAVA_HOME%\bin

M2_HOME = C:\apache-maven-3.6.0

MAVEN_BIN = %M2_HOME%\bin

MAVEN_HOME = %M2_HOME%

Under path Add these

%M2_HOME%

%JDK_HOME%

PHP Warning: PHP Startup: ????????: Unable to initialize module

brew reinstall php56-mcrypt --build-from-source

Do this—pass the --build-from-source flag—for each module which needs to be compiled with the same version.

It may also require PHP options depending on your plugins. If so, brew reinstall php56 --with-thread-safety

To see all of the options for php[version] run brew options php56 (replacing 56 with your version)

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

ant build.xml file doesn't exist

If you couldn't find the build.xml file in your project then you have to build it to be able to debug it and get your .apk

you can use this command-line to build:

android update project -p "project full path"

where "Project full path" -- Give your full path of your project location

after this you will find the build.xml then you can debug it.

- java.lang.NullPointerException - setText on null object reference

Here lies your problem:

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text); // tv is null
}

--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.

The error message is very clear and even tells you at what method. From the documentation:

public final View findViewById (int id)
    Look for a child view with the given id. If this view has the given id, return this view.
    Parameters
        id  The id to search for.
    Returns
        The view that has the given id in the hierarchy or null

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

In other words: You have no view with the id you give as a parameter.

error C2065: 'cout' : undeclared identifier

I have VS2010, Beta 1 and Beta 2 (one on my work machine and one at home), and I've used std plenty without issues. Try typing:

std::

And see if Intellisense gives you anything. If it gives you the usual stuff (abort, abs, acos, etc.), except for cout, well then, that is quite a puzzler. Definitely look into your C++ headers in that case.

Beyond that, I would just add to make sure you're running a regular, empty project (not CLR, where Intellisense is crippled), and that you've actually attempted to build the project at least once. As I mentioned in a comment, VS2010 parses files once you've added an include; it could be that something stuck the parser and it didn't "find" cout right away. (In which case, try restarting VS maybe?)

How to pass multiple arguments in processStartInfo?

It is purely a string:

startInfo.Arguments = "-sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

Of course, when arguments contain whitespaces you'll have to escape them using \" \", like:

"... -ss \"My MyAdHocTestCert.cer\""

See MSDN for this.

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have test classes you may:

1) Put a cursor on a class declaration and press Alt + Enter. In the dialogue choose JUnit and press Fix. This is a standard way to create test classes in IntelliJ.

2) Alternatively you may add JUnit jars manually (download from site or take from IntelliJ files).

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.

@invertedSpear's comment in that answer worked in firefox but not in any IE version.

So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if (fo) {
    hasFlash = true;
  }
} catch (e) {
  if (navigator.mimeTypes
        && navigator.mimeTypes['application/x-shockwave-flash'] != undefined
        && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
    hasFlash = true;
  }
}

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:

  1. Right click on Controller folder, and then select Add > Controller;
  2. Select MVC 5 Controller - Empty;
  3. Click in Add;
  4. Put HomeController for the controller name;
  5. Build the project and after Run your project again

I hope this help

How do I center text vertically and horizontally in Flutter?

I think a more flexible option would be to wrap the Text() with Align() like so:

Align(
  alignment: Alignment.center, // Align however you like (i.e .centerRight, centerLeft)
  child: Text("My Text"),
),

Using Center() seems to ignore TextAlign entirely on the Text widget. It will not align TextAlign.left or TextAlign.right if you try, it will remain in the center.

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

How to delete a whole folder and content?

use below method to delete entire main directory which contains files and it's sub directory. After calling this method once again call delete() directory of your main directory.

// For to Delete the directory inside list of files and inner Directory
public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
}

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I had this issue too, after following this guide, it was simply 1 additional patch that was required to get past the

Rule "Prior Visual Studio 2010 instances requiring update." failed.

Was to locate this file, and patch my machine

VS10sp1-KB983509.msp

Simply do a file search on the installation media for SQL Server 2012, in my case it was in \redist\VisualStudioShell (whereas in the guide it's listed as being in a different location).

Then hit 're-run'.

Failed State

How can I run a html file from terminal?

For those like me, who have reached this thread because they want to serve an html file from linux terminal or want to view it using a terminal command, use these steps:-

1)If you want to view your html using a browser:-
Navigate to the directory containing the html file
If you have chrome installed, Use:-

google-chrome <filename>.html


                OR
Use:-

firefox <filename>.html

2)If you want to serve html file and view it using a browser
Navigate to the directory containing the html file
And Simply type the following on the Terminal:-

pushd <filename>.html; python3 -m http.server 9999; popd;


Then click the I.P. address 0.0.0.0:9999 OR localhost:9999 (Whatever is the result after executing the above commands). Or type on the terminal :-

firefox 0.0.0.0:9999


Using the second method, anyone else connected to the same network can also view your file by using the URL:- "0.0.0.0:9999"

How to group by month from Date field using sql

Use the DATEPART function to extract the month from the date.

So you would do something like this:

SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)

What does "\r" do in the following script?

The '\r' character is the carriage return, and the carriage return-newline pair is both needed for newline in a network virtual terminal session.


From the old telnet specification (RFC 854) (page 11):

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

However, from the latest specification (RFC5198) (page 13):

  1. ...

  2. In Net-ASCII, CR MUST NOT appear except when immediately followed by either NUL or LF, with the latter (CR LF) designating the "new line" function. Today and as specified above, CR should generally appear only when followed by LF. Because page layout is better done in other ways, because NUL has a special interpretation in some programming languages, and to avoid other types of confusion, CR NUL should preferably be avoided as specified above.

  3. LF CR SHOULD NOT appear except as a side-effect of multiple CR LF sequences (e.g., CR LF CR LF).

So newline in Telnet should always be '\r\n' but most implementations have either not been updated, or keeps the old '\n\r' for backwards compatibility.

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

Docker: Container keeps on restarting again on again

tl;dr It is restarting with a status code of 127, meaning there is a missing file/library in your container. Starting a fresh container just might fix it.

Explanation:

As far as my understanding of Docker goes, this is what is happening:

  1. Container tries to start up. In the process, it tries to access a file/library which does not exist.
  2. It exits with a status code of 127, which is explained in this answer.
  3. Normally, this is where the container should have completely exited, but it restarts.
  4. It restarts because the restart policy must have been set to something other than no (the default), (using either the command line flag --restart or the docker-compose.yml key restart) while starting the container.

Solution: Something might have corrupted your container. Starting a fresh container should ideally do the job.

JOptionPane Yes or No window

You are writing if(true) so it will always show "Hello " message.

You should take decision on the basis of value of n returned.

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.

//on ubuntu server
sudo /etc/init.d/mysql start

To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.

$ sudo initctl stop mysql
$ sudo initctl start mysql

To verify the working, you can check the status of the service and get the process id (pid), simulate a failure by killing the "mysql" process and verify its status as running with new process id after sometime (typically within 1 minute) using the following commands.

$ sudo initctl status mysql         # get pid
$ sudo kill -9 <pid>                # kill mysql process
$ sudo initctl status mysql         # verify status as running after sometime

Note : In latest Ubuntu version now initctl is replaced by systemctl

Tab space instead of multiple non-breaking spaces ("nbsp")?

You can also use:

p::before {
    content: "";
    padding-left: 30px;
}

And replace "p" with any other selector you have in mind.

Permission denied when launch python script via bash

Do “chmod +x script”

Now try executing

How to change colors of a Drawable in Android?

If you have a drawable that's a solid color and you want to change it to a differnet solid color, you can use a ColorMatrixColorFilter. Transparency is preserved.

int iColor = Color.parseColor(color);

int red   = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue  = iColor & 0xFF;

float[] matrix = { 0, 0, 0, 0, red,
                   0, 0, 0, 0, green,
                   0, 0, 0, 0, blue,
                   0, 0, 0, 1, 0 };

ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);

scikit-learn random state in splitting dataset

For multiple times of execution of our model, random state make sure that data values will be same for training and testing data sets. It fixes the order of data for train_test_split

Angular - ui-router get previous state

For sake of readability, I'll place my solution (based of stu.salsbury's anwser) here.

Add this code to your app's abstract template so it runs on every page.

$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from, fromParams) {
    $rootScope.previousState = from.name;
    $rootScope.currentState = to.name;
    console.log('Previous state:'+$rootScope.previousState)
    console.log('Current state:'+$rootScope.currentState)
});

Keeps track of the changes in rootScope. Its pretty handy.

How to open SharePoint files in Chrome/Firefox

Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!

It gave me the idea to change the function _DispEx that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file: enter image description here

See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:

    /**
 * fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
 * @param  {HTMLElement} p the <A> element
 * @param  {HTMLEvent} a the click event
 * @param  {Boolean} h TRUE
 * @param  {Boolean} e FALSE
 * @param  {Boolean} g FALSE
 * @param  {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
 * @param  {Number} c 0
 * @param  {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
 * @param  {String} m
 * @param  {String} b the replacement URL to the xslviewer
 */
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
  bak_DispEx = _DispEx;
  _DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
    // if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
    // in that case we want to open ask the user if he/she wants to readonly or edit the file
    var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
    if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
      // if the URL doesn't start with http
      if (!/^http/.test(fileURL)) {
        fileURL = window.location.protocol + "//" + window.location.host + fileURL;
      }
      var ohtml = document.createElement('div');
      ohtml.style.padding = "10px";
      ohtml.style.display = "inline-block";
      ohtml.style.width = "200px";
      ohtml.style.width = "200px";
      ohtml.innerHTML = '<style>'
                      + '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
                      + '.opendocument_button:hover { box-shadow: none }'
                      + '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
                      + '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
                      + '</style>'
                      + 'You are about to open:'
                      + '<ul class="opendocument_ul">'
                      + '  <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
                      + '  <li>From: <b>'+window.location.hostname+'</b></li>'
                      + '</ul>'
                      + 'How would like to open this file?'
                      + '<ul class="opendocument_ul">'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
                      + '  <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
                      + '</ul>'
                      + '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
      // show the modal
      modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
        html:ohtml,
        dialogReturnValueCallback:function(ret) {
          if (ret!==-1) {
            if (ret === true) { // edit
              // reformat the fileURL
              var ext;
              if (/\.xlsx?$/.test(b)) ext = "ms-excel";
              if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
              fileURL = ext + ":ofe|u|" + fileURL;
            }
            window.location.href = fileURL; // open the file
          }
        }
      });
      a.preventDefault();
      a.stopImmediatePropagation()
      a.cancelBubble = true;
      a.returnValue = false;
      return false;
    }
    return bak_DispEx.apply(this, arguments);
  }
}, "sp.scriptloaded-core.js")

I use SP.SOD.executeOrDelayUntilEventNotified to make sure the function will be executed when core.js is loaded.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

MySQL Query GROUP BY day / month / year

You can do this simply Mysql DATE_FORMAT() function in GROUP BY. You may want to add an extra column for added clarity in some cases such as where records span several years then same month occurs in different years.Here so many option you can customize this. Please read this befor starting. Hope it should be very helpful for you. Here is sample query for your understanding

SELECT
    COUNT(id),
    DATE_FORMAT(record_date, '%Y-%m-%d') AS DAY,
    DATE_FORMAT(record_date, '%Y-%m') AS MONTH,
    DATE_FORMAT(record_date, '%Y') AS YEAR

FROM
    stats
WHERE
    YEAR = 2009
GROUP BY
    DATE_FORMAT(record_date, '%Y-%m-%d ');

Saving ssh key fails

If you prefer to use a GUI to create the keys

  1. Use Putty Gen to generate a key
  2. Export the key as an open SSH key
  3. As mentioned by @VonC create the .ssh directory and then you can drop the private and public keys in there
  4. Or use a GUI program (like Tortoise Git) to use the SSH keys

For a walkthrough on putty gen for the above steps, please see http://ask-leo.com/how_do_i_create_and_use_public_keys_with_ssh.html

How to convert ISO8859-15 to UTF8?

I have ubuntu 14 and the other answers where no working for me

iconv -f ISO-8859-1 -t UTF-8 in.tex > out.tex

I found this command here

Right pad a string with variable number of spaces

Whammo blammo (for leading spaces):

SELECT 
    RIGHT(space(60) + cust_name, 60),
    RIGHT(space(60) + cust_address, 60)

OR (for trailing spaces)

SELECT
    LEFT(cust_name + space(60), 60),
    LEFT(cust_address + space(60), 60),

How to add hyperlink in JLabel?

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

How to use the PRINT statement to track execution as stored procedure is running?

I'm sure you can use RAISERROR ... WITH NOWAIT

If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

In C#, I had problem with checking RadioButton, and this worked for me:

driver.ExecuteJavaScript("arguments[0].checked=true", radio);

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

Check if a variable exists in a list in Bash

An alternative solution inspired by the accepted response, but that uses an inverted logic:

MODE="${1}"

echo "<${MODE}>"
[[ "${MODE}" =~ ^(preview|live|both)$ ]] && echo "OK" || echo "Uh?"

Here, the input ($MODE) must be one of the options in the regular expression ('preview', 'live', or 'both'), contrary to matching the whole options list to the user input. Of course, you do not expect the regular expression to change.

How to get the last row of an Oracle a table

The last row according to a strict total order over composite key K(k1, ..., kn):

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

Given the special case where K is simple (i.e. not composite), the above is shortened to:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

Note that for this query to return just one row the key must order without ties. If ties are allowed, this query will return all the rows tied with the greatest key.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Extract images from PDF without resampling, in python?

After some searching I found the following script which works really well with my PDF's. It does only tackle JPG, but it worked perfectly with my unprotected files. Also is does not require any outside libraries.

Not to take any credit, the script originates from Ned Batchelder, and not me. Python3 code: extract jpg's from pdf's. Quick and dirty

import sys

with open(sys.argv[1],"rb") as file:
    file.seek(0)
    pdf = file.read()

startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0

njpg = 0
while True:
    istream = pdf.find(b"stream", i)
    if istream < 0:
        break
    istart = pdf.find(startmark, istream, istream + 20)
    if istart < 0:
        i = istream + 20
        continue
    iend = pdf.find(b"endstream", istart)
    if iend < 0:
        raise Exception("Didn't find end of stream!")
    iend = pdf.find(endmark, iend - 20)
    if iend < 0:
        raise Exception("Didn't find end of JPG!")

    istart += startfix
    iend += endfix
    print("JPG %d from %d to %d" % (njpg, istart, iend))
    jpg = pdf[istart:iend]
    with open("jpg%d.jpg" % njpg, "wb") as jpgfile:
        jpgfile.write(jpg)

    njpg += 1
    i = iend

Getting all types that implement an interface

This worked for me. It loops though the classes and checks to see if they are derrived from myInterface

 foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                 .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
    //do stuff
 }

Error 'tunneling socket' while executing npm install

I had this same error when trying to install Cypress via npm. I tried many of the above solutions as I am behind a proxy, but was still seeing the same error. In the end I found that my WIndows system configuration(can be checked by entering 'set' in command prompt) had HTTP and HTTPS proxys set that differed from the ones vonfigure in npm. I deleted these proxys and it downloaded staright away.

How do I include the string header?

"apstring" is not standard C++, in C++, you'd want to #include the <string> header.

Powershell: How can I stop errors from being displayed in a script?

If you want the powershell errormessage for a cmdlet suppressed, but still want to catch the error, use "-erroraction 'silentlyStop'"

How to find substring inside a string (or how to grep a variable)?

expr match "$LIST" '$SOURCE'

don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:

expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"

The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also

expr "$LIST" : ".*\($SOURCE\)"

This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

install using adb with command ./adb install -r abc.apk will solve the problem (it will overwrite even when the device has higher app version)

How to revert multiple git commits?

If you want to temporarily revert the commits of a feature, then you can use the series of following commands.

Here is how it works

git log --pretty=oneline | grep 'feature_name' | cut -d ' ' -f1 | xargs -n1 git revert --no-edit

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

Where are SQL Server connection attempts logged?

If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.

Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.

If you want to audit a client application name along with each failed login, you can use an Extended Events session.

To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/

Algorithm for Determining Tic Tac Toe Game Over

I was asked the same question in one of my interviews. My thoughts: Initialize the matrix with 0. Keep 3 arrays 1)sum_row (size n) 2) sum_column (size n) 3) diagonal (size 2)

For each move by (X) decrement the box value by 1 and for each move by (0) increment it by 1. At any point if the row/column/diagonal which has been modified in current move has sum either -3 or +3 means somebody has won the game. For a draw we can use above approach to keep the moveCount variable.

Do you think I am missing something ?

Edit: Same can be used for nxn matrix. Sum should be even +3 or -3.

Read url to string in few lines of java code

Now that more time has passed, here's a way to do it in Java 8:

URLConnection conn = url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
    pageText = reader.lines().collect(Collectors.joining("\n"));
}

How to get raw text from pdf file using java

For the newer versions of Apache pdfbox. Here is the example from the original source

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pdfbox.examples.util;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.text.PDFTextStripper;

/**
 * This is a simple text extraction example to get started. For more advance usage, see the
 * ExtractTextByArea and the DrawPrintTextLocations examples in this subproject, as well as the
 * ExtractText tool in the tools subproject.
 *
 * @author Tilman Hausherr
 */
public class ExtractTextSimple
{
    private ExtractTextSimple()
    {
        // example class should not be instantiated
    }

    /**
     * This will print the documents text page by page.
     *
     * @param args The command line arguments.
     *
     * @throws IOException If there is an error parsing or extracting the document.
     */
    public static void main(String[] args) throws IOException
    {
        if (args.length != 1)
        {
            usage();
        }

        try (PDDocument document = PDDocument.load(new File(args[0])))
        {
            AccessPermission ap = document.getCurrentAccessPermission();
            if (!ap.canExtractContent())
            {
                throw new IOException("You do not have permission to extract text");
            }

            PDFTextStripper stripper = new PDFTextStripper();

            // This example uses sorting, but in some cases it is more useful to switch it off,
            // e.g. in some files with columns where the PDF content stream respects the
            // column order.
            stripper.setSortByPosition(true);

            for (int p = 1; p <= document.getNumberOfPages(); ++p)
            {
                // Set the page interval to extract. If you don't, then all pages would be extracted.
                stripper.setStartPage(p);
                stripper.setEndPage(p);

                // let the magic happen
                String text = stripper.getText(document);

                // do some nice output with a header
                String pageStr = String.format("page %d:", p);
                System.out.println(pageStr);
                for (int i = 0; i < pageStr.length(); ++i)
                {
                    System.out.print("-");
                }
                System.out.println();
                System.out.println(text.trim());
                System.out.println();

                // If the extracted text is empty or gibberish, please try extracting text
                // with Adobe Reader first before asking for help. Also read the FAQ
                // on the website: 
                // https://pdfbox.apache.org/2.0/faq.html#text-extraction
            }
        }
    }

    /**
     * This will print the usage for this document.
     */
    private static void usage()
    {
        System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
        System.exit(-1);
    }
}

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

How to download/upload files from/to SharePoint 2013 using CSOM?

Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
    Try
        destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
        Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
        Dim down As Stream = System.IO.File.Create(destinationPath)
        Dim a As Integer = fi.Stream.ReadByte()
        While a <> -1
            down.WriteByte(CType(a, Byte))
            a = fi.Stream.ReadByte()
        End While
    Catch ex As Exception
        ToLog(Type.ERROR, ex.Message)
    End Try
End Sub

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

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

Excel formula to get cell color

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let's say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

Undoing a 'git push'

Undo multiple commits git reset --hard 0ad5a7a6 (Just provide commit SHA1 hash)

Undo last commit

git reset --hard HEAD~1 (changes to last commit will be removed ) git reset --soft HEAD~1 (changes to last commit will be available as uncommited local modifications)

MySQL skip first 10 results

select * from table where id not in (select id from table limit 10)

where id be the key in your table.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

How to use FormData in react-native?

Providing some other solution; we're also using react-native-image-picker; and the server side is using koa-multer; this set-up is working good:

ui

ImagePicker.showImagePicker(options, (response) => {
      if (response.didCancel) {}
      else if (response.error) {}
      else if (response.customButton) {}
      else {
        this.props.addPhoto({ // leads to handleAddPhoto()
          fileName: response.fileName,
          path: response.path,
          type: response.type,
          uri: response.uri,
          width: response.width,
          height: response.height,
        });
      }
    });

handleAddPhoto = (photo) => { // photo is the above object
    uploadImage({ // these 3 properties are required
      uri: photo.uri,
      type: photo.type,
      name: photo.fileName,
    }).then((data) => {
      // ...
    });
  }

client

export function uploadImage(file) { // so uri, type, name are required properties
  const formData = new FormData();
  formData.append('image', file);

  return fetch(`${imagePathPrefix}/upload`, { // give something like https://xx.yy.zz/upload/whatever
    method: 'POST',
    body: formData,
  }
  ).then(
    response => response.json()
  ).then(data => ({
    uri: data.uri,
    filename: data.filename,
  })
  ).catch(
    error => console.log('uploadImage error:', error)
  );
}

server

import multer from 'koa-multer';
import RouterBase from '../core/router-base';

const upload = multer({ dest: 'runtime/upload/' });

export default class FileUploadRouter extends RouterBase {
  setupRoutes({ router }) {
    router.post('/upload', upload.single('image'), async (ctx, next) => {
      const file = ctx.req.file;
      if (file != null) {
        ctx.body = {
          uri: file.filename,
          filename: file.originalname,
        };
      } else {
        ctx.body = {
          uri: '',
          filename: '',
        };
      }
    });
  }
}

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}