Programs & Examples On #Back button control

C++ JSON Serialization

Does anything, easy like that, exists?? THANKS :))

C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.

You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.

In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

How to iterate a loop with index and element in Swift

Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated() method to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:

for (index, element) in list.enumerated() {
  print("Item \(index): \(element)")
}

Before Swift 3.0 and after Swift 2.0, the function was called enumerate():

for (index, element) in list.enumerate() {
    print("Item \(index): \(element)")
}

Prior to Swift 2.0, enumerate was a global function.

for (index, element) in enumerate(list) {
    println("Item \(index): \(element)")
}

Can you write nested functions in JavaScript?

Is this really possible.

Yes.

_x000D_
_x000D_
function a(x) {    // <-- function_x000D_
  function b(y) { // <-- inner function_x000D_
    return x + y; // <-- use variables from outer scope_x000D_
  }_x000D_
  return b;       // <-- you can even return a function._x000D_
}_x000D_
console.log(a(3)(4));
_x000D_
_x000D_
_x000D_

How to write log base(2) in c/c++

I needed to have more precision that just the position of the most significant bit, and the microcontroller I was using had no math library. I found that just using a linear approximation between 2^n values for positive integer value arguments worked well. Here is the code:

uint16_t approx_log_base_2_N_times_256(uint16_t n)
{
    uint16_t msb_only = 0x8000;
    uint16_t exp = 15;

    if (n == 0)
        return (-1);
    while ((n & msb_only) == 0) {
        msb_only >>= 1;
        exp--;
    }

    return (((uint16_t)((((uint32_t) (n ^ msb_only)) << 8) / msb_only)) | (exp << 8));
}

In my main program, I needed to calculate N * log2(N) / 2 with an integer result:

temp = (((uint32_t) N) * approx_log_base_2_N_times_256) / 512;

and all 16 bit values were never off by more than 2%

How can I increment a char?

In Python 2.x, just use the ord and chr functions:

>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>> 

Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord receives Unicode chars and chr produces them).

But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:

>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'

How to call function of one php file from another php file and pass parameters to it?

file1.php

<?php

    function func1($param1, $param2)
    {
        echo $param1 . ', ' . $param2;
    }

file2.php

<?php

    require_once('file1.php');

    func1('Hello', 'world');

See manual

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

How can I commit a single file using SVN over a network?

You have a file myFile.txt you want to commit.

The right procedure is :

  1. Move to the file folder
  2. svn up
  3. svn commit myFile.txt -m "Insert here a commit message!!!"

Hope this will help someone.

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

RecyclerView vs. ListView

I think the main and biggest difference they have is that ListView looks for the position of the item while creating or putting it, on the other hand RecyclerView looks for the type of the item. if there is another item created with the same type RecyclerView does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView doesn't try to create same type. ListView doesn't have a this kind of pooling mechanism.

Copying text to the clipboard using Java

The following class allows you to copy/paste a String to/from the clipboard.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;

import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();
        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
        robot.keyPress(controlKey);
        robot.keyPress(VK_V);
        robot.keyRelease(controlKey);
        robot.keyRelease(VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        return defaultToolkit.getSystemClipboard();
    }
}

Selecting the last value of a column

Is it acceptable to answer the original question with a strictly off topic answer:) You can write a formula in the spreadsheet to do this. Ugly perhaps? but effective in the normal operating of a spreadsheet.

=indirect("R"&ArrayFormula(max((G:G<>"")*row(G:G)))&"C"&7)


(G:G<>"") gives an array of true false values representing non-empty/empty cells
(G:G<>"")*row(G:G) gives an array of row numbers with zeros where cell is empty
max((G:G<>"")*row(G:G)) is the last non-empty cell in G

This is offered as a thought for a range of questions in the script area that could be delivered reliably with array formulas which have the advantage of often working in similar fashion in excel and openoffice.

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Sometimes implicit wait seems to get overridden and wait time is cut short. [@eugene.polschikov] had good documentation on the whys. I have found in my testing and coding with Selenium 2 that implicit waits are good but occasionally you have to wait explicitly.

It is better to avoid directly calling for a thread to sleep, but sometimes there isn't a good way around it. However, there are other Selenium provided wait options that help. waitForPageToLoad and waitForFrameToLoad have proved especially useful.

Set width to match constraints in ConstraintLayout

match_parent is not supported by ConstraintLayout. Set width to 0dp to let it match constraints.

What is the best way to seed a database in Rails?

Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.

How to reduce the image file size using PIL

lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:

from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)

hope it helps to anyone stumbling upon it.

How to darken an image on mouseover?

I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.

outerLink {
    overflow: hidden;
    position: relative;
}

outerLink:hover:after {
    background: #000;
    content: "";
    display: block;
    height: 100%;
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 100%;
}

How do I use a regular expression to match any string, but at least 3 characters?

You could try with simple 3 dots. refer to the code in perl below

$a =~ m /.../ #where $a is your string

Cannot simply use PostgreSQL table name ("relation does not exist")

I had problems with this and this is the story (sad but true) :

  1. If your table name is all lower case like : accounts you can use: select * from AcCounTs and it will work fine

  2. If your table name is all lower case like : accounts The following will fail: select * from "AcCounTs"

  3. If your table name is mixed case like : Accounts The following will fail: select * from accounts

  4. If your table name is mixed case like : Accounts The following will work OK: select * from "Accounts"

I dont like remembering useless stuff like this but you have to ;)

Call a React component method from outside

With React17 you can use useImperativeHandle hook.

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef:

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.focus();
        }
    }));

    return <input ref={inputRef} ... />;
}

FancyInput = forwardRef(FancyInput);

In this example, a parent component that renders would be able to call inputRef.current.focus().

How to figure out the SMTP server host?

To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

Put this in a batch file named: getmns.bat (get mail name server):

@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.

For example:

getmns google.com

output:

google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com

alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com      internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27

For example to pipe the result again into a file do:

getmns google.com > google.mns.txt

:-D

HTML form do some "action" when hit submit button

index.html

<!DOCTYPE html>
<html>
   <body>
       <form action="submit.php" method="POST">
         First name: <input type="text" name="firstname" /><br /><br />
         Last name: <input type="text" name="lastname" /><br />
         <input type="submit" value="Submit" />
      </form> 
   </body>
</html>

After that one more file which page you want to display after pressing the submit button

submit.php

<html>
  <body>

    Your First Name is -  <?php echo $_POST["firstname"]; ?><br>
    Your Last Name is -   <?php echo $_POST["lastname"]; ?>

  </body>
</html>

Capturing count from an SQL query

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

Alternative to itoa() for converting integer to string C++?

In C++11 you can use std::to_string:

#include <string>

std::string s = std::to_string(5);

If you're working with prior to C++11, you could use C++ streams:

#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();

Taken from http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

Detecting an "invalid date" Date instance in JavaScript

Inspired by Borgar's approach I have made sure that the code not only validates the date, but actually makes sure the date is a real date, meaning that dates like 31/09/2011 and 29/02/2011 are not allowed.

function(dateStr) {
    s = dateStr.split('/');
    d = new Date(+s[2], s[1]-1, +s[0]);
    if (Object.prototype.toString.call(d) === "[object Date]") {
        if (!isNaN(d.getTime()) && d.getDate() == s[0] && 
            d.getMonth() == (s[1] - 1)) {
            return true;
        }
    }
    return "Invalid date!";
}

Convert array to string in NodeJS

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.

Put spacing between divs in a horizontal row?

Quite a few ways to apprach this problem.

Use the box-sizing css3 property and simulate the margins with borders.

http://jsfiddle.net/Z7mFr/1/

div.inside {
 width: 25%;
 float:left;
 border-right: 5px solid grey;
 background-color: blue;
 box-sizing:border-box;
 -moz-box-sizing:border-box; /* Firefox */
 -webkit-box-sizing:border-box; /* Safari */
}

<div style="width:100%; height: 200px; background-color: grey;">
 <div class="inside">A</div>
 <div class="inside">B</div>
 <div class="inside">C</div>
 <div class="inside">D</div>
</div>

Reduce the percentage of your elements widths and add some margin-right.

http://jsfiddle.net/mJfz3/

.outer {
 width:100%;
 background:#999;
 overflow:auto;
}

.inside {
 float:left;
 width:24%;
 margin-right:1%;
 background:#333;
}

How to loop through a collection that supports IEnumerable?

or even a very classic old fashion method

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // do your stuff   
}

maybe you would like this method also :-)

What is the best way to compare floats for almost-equality in Python?

Useful for the case where you want to make sure 2 numbers are the same 'up to precision', no need to specify the tolerance:

  • Find minimum precision of the 2 numbers

  • Round both of them to minimum precision and compare

def isclose(a,b):                                       
    astr=str(a)                                         
    aprec=len(astr.split('.')[1]) if '.' in astr else 0 
    bstr=str(b)                                         
    bprec=len(bstr.split('.')[1]) if '.' in bstr else 0 
    prec=min(aprec,bprec)                                      
    return round(a,prec)==round(b,prec)                               

As written, only works for numbers without the 'e' in their string representation ( meaning 0.9999999999995e-4 < number <= 0.9999999999995e11 )

Example:

>>> isclose(10.0,10.049)
True
>>> isclose(10.0,10.05)
False

How to validate domain name in PHP?

The correct answer is that you don't ... you let a unit tested tool do the work for you:

// return '' if host invalid --
private function setHostname($host = '')
{
    $ret = (!empty($host)) ? $host : '';
    if(filter_var('http://'.$ret.'/', FILTER_VALIDATE_URL) === false) {
        $ret = '';
    }
    return $ret;
}

further reading :https://www.w3schools.com/php/filter_validate_url.asp

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

IEnumerable<string> e = (from char c in source
                        select new { Data = c.ToString() }).Select(t = > t.Data);
// or
IEnumerable<string> e = from char c in source
                        select c.ToString();
// or
IEnumerable<string> e = source.Select(c = > c.ToString());

Then you can call ToList():

List<string> l = (from char c in source
                  select new { Data = c.ToString() }).Select(t = > t.Data).ToList();
// or
List<string> l = (from char c in source
                  select c.ToString()).ToList();
// or
List<string> l = source.Select(c = > c.ToString()).ToList();

How can I use Python to get the system hostname?

If I'm correct, you're looking for the socket.gethostname function:

>> import socket
>> socket.gethostname()
'terminus'

How to get "GET" request parameters in JavaScript?

You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

Parsing JSON from URL

I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper

ObjectMapper mapper = new ObjectMapper();
Integer      value = mapper.readValue(new URL("your url here"), Integer.class);

Integer.class can be also a complex type. Just for example used.

How can I stop a While loop?

The is operator in Python probably doesn't do what you expect. Instead of this:

    if numpy.array_equal(tmp,universe_array) is True:
        break

I would write it like this:

    if numpy.array_equal(tmp,universe_array):
        break

The is operator tests object identity, which is something quite different from equality.

How to fix homebrew permissions?

I didn't want to muck around with folder permissions yet so I did the following:

brew doctor
brew upgrade
brew cleanup

I was then able to continue installing my other brew formula successfully.

Listing only directories using ls in Bash?

If a hidden directory is not needed to be listed, I offer:

ls -l | grep "^d" | awk -F" " '{print $9}'

And if hidden directories are needed to be listed, use:

ls -Al | grep "^d" | awk -F" " '{print $9}'

Or

find -maxdepth 1 -type d | awk -F"./" '{print $2}'

What are the use cases for selecting CHAR over VARCHAR in SQL?

Many people have pointed out that if you know the exact length of the value using CHAR has some benefits. But while storing US states as CHAR(2) is great today, when you get the message from sales that 'We have just made our first sale to Australia', you are in a world of pain. I always send to overestimate how long I think fields will need to be rather than making an 'exact' guess to cover for future events. VARCHAR will give me more flexibility in this area.

How can I check if character in a string is a letter? (Python)

This works:

word = str(input("Enter string:"))
notChar = 0
isChar = 0
for char in word:
    if not char.isalpha():
        notChar += 1
    else:
        isChar += 1
print(isChar, " were letters; ", notChar, " were not letters.")

MongoDB: Is it possible to make a case-insensitive query?

Starting with MongoDB 3.4, the recommended way to perform fast case-insensitive searches is to use a Case Insensitive Index.

I personally emailed one of the founders to please get this working, and he made it happen! It was an issue on JIRA since 2009, and many have requested the feature. Here's how it works:

A case-insensitive index is made by specifying a collation with a strength of either 1 or 2. You can create a case-insensitive index like this:

db.cities.createIndex(
  { city: 1 },
  { 
    collation: {
      locale: 'en',
      strength: 2
    }
  }
);

You can also specify a default collation per collection when you create them:

db.createCollection('cities', { collation: { locale: 'en', strength: 2 } } );

In either case, in order to use the case-insensitive index, you need to specify the same collation in the find operation that was used when creating the index or the collection:

db.cities.find(
  { city: 'new york' }
).collation(
  { locale: 'en', strength: 2 }
);

This will return "New York", "new york", "New york" etc.

Other notes

  • The answers suggesting to use full-text search are wrong in this case (and potentially dangerous). The question was about making a case-insensitive query, e.g. username: 'bill' matching BILL or Bill, not a full-text search query, which would also match stemmed words of bill, such as Bills, billed etc.

  • The answers suggesting to use regular expressions are slow, because even with indexes, the documentation states:

    "Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes."

    $regex answers also run the risk of user input injection.

Upgrade to python 3.8 using conda

Update for 2020/07

Finally, Anaconda3-2020.07 is out and its core is Python 3.8!

You can now download Anaconda packed with Python 3.8 goodness at:

Password encryption/decryption code in .NET

One of the simplest methods of encryption (if you absolutely MUST make one up yourself since .NET has such awesome encryption libraries already [as provided by Cogwheel just before me]) is to XOR the ASCII value of each character of the input string against a known "key" value. XOR functionality in C# is accomplished using the ^ key I believe.

Then you can convert the values back from the result of the XOR to ASCII Chars, and store them in the database. This is not highly secure, but it is one of the easiest encryption methods.

Also, if using an access database, I've found that some characters when put in front of a string make the entire field unreadable when opening the database itself. But the field is still readable by your app even though it is blank to a malicious user. But who uses access anymore anyway right?

E: Unable to locate package npm

For Debian Stretch (Debian version 9), nodejs does not include npm, and to install it as a separate package, you have to enable stretch-backports.

echo 'deb http://deb.debian.org/debian stretch-backports main' |
sudo tee /etc/apt/sources.list.d/stretch-backports.list
apt-get update -y
apt-get -t stretch-backports install -y npm

In Buster (Debian 10), npm is a regular package, so going forward, this should just work. But some of us will still be stuck partially on Stretch boxes for some time to come.

Xcode error "Could not find Developer Disk Image"

If you have iOS 9.1 on your phone, just download Xcode 7.1 beta instead of using GM.

See Apple's response: Could not find developer disk image for iOS 9.1

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World! in the JavaScript alert.

You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

How do I install soap extension?

Please follow the below steps :

 1) Locate php.ini in your apache bin folder, I.e Apache/bin/php.ini
 2) Remove the ; from the beginning of extension=php_soap.dll
 3) Restart your Apache server (by using : 
    # /etc/init.d/apache2 restart OR 
    $ sudo /etc/init.d/apache2 restart OR 
    $ sudo service apache2 restart)
 4) Look up your phpinfo();

 you may check here as well,if this does not solve your issue:  
 https://www.php.net/manual/en/soap.requirements.php

Differences between hard real-time, soft real-time, and firm real-time?

The simplest way to distinguish between the different kinds of real-time system types is answering the question:

Is a delayed system response (after the deadline) is still useful or not?

So depending on the answer you get for this question, your system could be included as one of the following categories:

  1. Hard: No, and delayed answers are considered a system failure

This is the case when missing the dead-line will make the system unusable. For example the system controlling the car Airbag system should detect the crash and inflate rapidly the bag. The whole process takes more or less one-twenty-fifth of a second. Thus, if the system for example react with 1 second of delay the consequences could be mortal and it will be no benefit having the bag inflated once the car has already crashed.

  1. Firm: No, but delayed answers are not necessary a system failure

This is the case when missing the deadline is tolerable but it will affect the quality of the service. As a simple example consider a video encryption system. Normally the password of encryption is generated in the server (video Head end) and sent to the customer set-top box. This process should be synchronized so normally the set-top box receives the password before starts receiving the encrypted video frames. In this case a delay it may lead to video glitches since the set-top box is not able to decode the frames because it hasn't received the password yet. In this case the service (film, an interesting football match, etc) could be affected by not meeting the deadline. Receiving the password with delay in this case is not useful since the frames encrypted with the same have already caused the glitches.

  1. Soft: Yes, but the system service is degraded

As from the the wikipedia description the usefulness of a result degrades after its deadline. That means, getting a response from the system out of the deadline is still useful for the end user but its usefulness degrade after reaching the deadline. A simple example for this case is a software that automatically controls the temperature of a room (or a building). In this case if the system has some delays reading the temperature sensors it will be a little bit slow to react upon brusque temperature changes. However, at the end it will end up reacting to the change and adjusting accordingly the temperature to keep it constant for example. So in this case the delayed reaction is useful, but it degrades the system quality of service.

Allow only numbers and dot in script

_x000D_
_x000D_
function isNumberKey(evt,id)_x000D_
{_x000D_
 try{_x000D_
        var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
  _x000D_
        if(charCode==46){_x000D_
            var txt=document.getElementById(id).value;_x000D_
            if(!(txt.indexOf(".") > -1)){_x000D_
 _x000D_
                return true;_x000D_
            }_x000D_
        }_x000D_
        if (charCode > 31 && (charCode < 48 || charCode > 57) )_x000D_
            return false;_x000D_
_x000D_
        return true;_x000D_
 }catch(w){_x000D_
  alert(w);_x000D_
 }_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
  </head>_x000D_
  <body>_x000D_
    <INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I switch my git repository to a particular commit

To create a new branch (locally):

  • With the commit hash (or part of it)

    git checkout -b new_branch 6e559cb
    
  • or to go back 4 commits from HEAD

    git checkout -b new_branch HEAD~4
    

Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch


For discarding the last three commits, see Lunaryorn's answer below.


For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

NPM global install "cannot find module"

For some (like me) that nothing else worked, try this:

brew cleanup
brew link node
brew uninstall node
brew install node

Hope it helps someone :)

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

"python" not recognized as a command

Python comes with a small utility that fixes this. From the command line run:

c:\python27\tools\scripts\win_add2path.py

Make sure you close the command window (with exit or the close button) and open it again.

Bring element to front using CSS

Another Note: z-index must be considered when looking at children objects relative to other objects.

For example

<div class="container">
    <div class="branch_1">
        <div class="branch_1__child"></div>
    </div>
    <div class="branch_2">
        <div class="branch_2__child"></div>
    </div>
</div>

If you gave branch_1__child a z-index of 99 and you gave branch_2__child a z-index of 1, but you also gave your branch_2 a z-index of 10 and your branch_1 a z-index of 1, your branch_1__child still will not show up in front of your branch_2__child

Anyways, what I'm trying to say is; if a parent of an element you'd like to be placed in front has a lower z-index than its relative, that element will not be placed higher.

The z-index is relative to its containers. A z-index placed on a container farther up in the hierarchy basically starts a new "layer"

Incep[inception]tion

Here's a fiddle to play around:

https://jsfiddle.net/orkLx6o8/

@viewChild not working - cannot read property nativeElement of undefined

Initializing the Canvas like below works for TypeScript/Angular solutions.

const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId"); 

const context = canvas.getContext("2d"); 

Parse (split) a string in C++ using string delimiter (standard C++)

You can also use regex for this:

std::vector<std::string> split(const std::string str, const std::string regex_str)
{
    std::regex regexz(regex_str);
    std::vector<std::string> list(std::sregex_token_iterator(str.begin(), str.end(), regexz, -1),
                                  std::sregex_token_iterator());
    return list;
}

which is equivalent to :

std::vector<std::string> split(const std::string str, const std::string regex_str)
{
    std::sregex_token_iterator token_iter(str.begin(), str.end(), regexz, -1);
    std::sregex_token_iterator end;
    std::vector<std::string> list;
    while (token_iter != end)
    {
        list.emplace_back(*token_iter++);
    }
    return list;
}

and use it like this :

#include <iostream>
#include <string>
#include <regex>

std::vector<std::string> split(const std::string str, const std::string regex_str)
{   // a yet more concise form!
    return { std::sregex_token_iterator(str.begin(), str.end(), std::regex(regex_str), -1), std::sregex_token_iterator() };
}

int main()
{
    std::string input_str = "lets split this";
    std::string regex_str = " "; 
    auto tokens = split(input_str, regex_str);
    for (auto& item: tokens)
    {
        std::cout<<item <<std::endl;
    }
}

play with it online! http://cpp.sh/9sumb

you can simply use substrings, characters, etc like normal, or use actual regular expressions to do the splitting.
its also concise and C++11!

Python Pandas Counting the Occurrences of a Specific value

easy but not efficient:

list(df.education).count('9th')

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

Check if a number is int or float

how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

Send email using the GMail SMTP server from a PHP page

I have a solution for GSuite accounts that doesnt have the "@gmail.com" sufix. Also I think it will work for GSuite accounts with the @gmail.com but havent tried it. First you should have the privileges to change the option "allos¿w less secure app" for your GSuite account. If you have the privileges (you can check in account settings->security) then you have to deactivate "two step factor authentication" go to the end of the page and set to "yes" for allow less secure applications. That's all. If you dont have privileges to change those options the solution for this thread will not work. Check https://support.google.com/a/answer/6260879?hl=en to make changes to "allow less..." option.

Android ViewPager with bottom dots

I thought of posting a simpler solution for the above problem and indicator numbers can be dynamically changed with only changing one variable value dotCounts=x what I did goes like this.

1) Create an xml file in drawable folder for page selected indicator named "item_selected".

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" android:useLevel="true"
    android:dither="true">
    <size android:height="8dp" android:width="8dp"/>
    <solid android:color="@color/image_item_selected_for_dots"/>
</shape>

2) Create one more xml file for unselected indicator named "item_unselected"

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" android:useLevel="true"
    android:dither="true">

    <size android:height="8dp" android:width="8dp"/>

    <solid android:color="@color/image_item_unselected_for_dots"/>
</shape>

3) Now add add this part of the code at the place where you want to display the indicators for ex below viewPager in your Layout XML file.

 <RelativeLayout
        android:id="@+id/viewPagerIndicator"
        android:layout_width="match_parent"
        android:layout_below="@+id/banner_pager"
        android:layout_height="wrap_content"
        android:gravity="center">

        <LinearLayout
            android:id="@+id/viewPagerCountDots"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:orientation="horizontal" />
        </RelativeLayout>

4) Add this function on top of your activity file file where your layout is inflated or the above xml file is related to

private int dotsCount=5;    //No of tabs or images
private ImageView[] dots;
LinearLayout linearLayout;

private void drawPageSelectionIndicators(int mPosition){
    if(linearLayout!=null) {
        linearLayout.removeAllViews();
    }
    linearLayout=(LinearLayout)findViewById(R.id.viewPagerCountDots);
    dots = new ImageView[dotsCount];
    for (int i = 0; i < dotsCount; i++) {
        dots[i] = new ImageView(context);
        if(i==mPosition)
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.item_selected));
        else
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.item_unselected));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );

        params.setMargins(4, 0, 4, 0);
        linearLayout.addView(dots[i], params);
    }
}

5) Finally in your onCreate method add the following code to reference your layout and handle pageselected positions

drawPageSelectionIndicators(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        drawPageSelectionIndicators(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});

Android: converting String to int

You just need to write the line of code to convert your string to int.

 int convertedVal = Integer.parseInt(YOUR STR);

Drop shadow for PNG image in CSS

Here is ready glow hover animation code snippet for this:

http://codepen.io/widhi_allan/pen/ltaCq

-webkit-filter: drop-shadow(0px 0px 0px rgba(255,255,255,0.80));

Changing the color of a clicked table row using jQuery

Here's a possible solution that will color the entire row for your table.

CSS

tr.highlighted td {
    background: red;
}

jQuery

$('#data tr').click(function(e) {
    $('#data tr').removeClass('highlighted');
    $(this).toggleClass('highlighted');   
});

Demo: http://jsfiddle.net/jrthib/HVw7E/2/

Java SecurityException: signer information does not match

  1. After sign, access: dist\lib
  2. Find extra .jar
  3. Using Winrar, You extract for a folder (extract to "folder name") option
  4. Access: META-INF/MANIFEST.MF
  5. Delete each signature like that:

Name: net/sf/jasperreports/engine/util/xml/JaxenXPathExecuterFactory.c lass SHA-256-Digest: q3B5wW+hLX/+lP2+L0/6wRVXRHq1mISBo1dkixT6Vxc=

  1. Save the file
  2. Zip again
  3. Renaime ext to .jar back
  4. Already

Rename all files in a folder with a prefix in a single command

find -execdir rename

This renames files and directories with a regular expression affecting only basenames.

So for a prefix you could do:

PATH=/usr/bin find . -depth -execdir rename 's/^/Unix_/' '{}' \;

or to affect files only:

PATH=/usr/bin find . -type f -execdir rename 's/^/Unix_/' '{}' \;

-execdir first cds into the directory before executing only on the basename.

I have explained it in more detail at: Find multiple files and rename them in Linux

What's the difference between process.cwd() vs __dirname?

$ find proj

proj
proj/src
proj/src/index.js

$ cat proj/src/index.js

console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);

$ cd proj; node src/index.js

process.cwd() = /tmp/proj
__dirname = /tmp/proj/src

Viewing all defined variables

To get the names:

for name in vars().keys():
  print(name)

To get the values:

for value in vars().values():
  print(value)

vars() also takes an optional argument to find out which vars are defined within an object itself.

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

You can create a custom layout and apply it to the actionBar.

To do so, follow those 2 simple steps:

  1. Java Code

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(R.layout.actionbar);
    

Where R.layout.actionbar is the following layout.

  1. XML

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/action_bar_title"
        android:text="YOUR ACTIVITY TITLE"
        android:textColor="#ffffff"
        android:textSize="24sp" />
    </LinearLayout>
    

It can be as complex as you want. Try it out!

EDIT:

To set the background you can use the property android:background in the container layout (LinearLayout in that case). You may need to set the layout height android:layout_height to match_parent instead of wrap_content.

Moreover, you can also add a LOGO / ICON to it. To do so, simply add an ImageView inside your layout, and set layout orientation property android:orientation to horizontal (or simply use a RelativeLayout and manage it by yourself).

To change the title of above custom action bar dynamically, do this:

TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

laravel Eloquent ORM delete() method

Laravel Eloquent provides destroy() function in which returns boolean value. So if a record exists on the database and deleted you'll get true otherwise false.

Here's an example using Laravel Tinker shell.

delete operation result

In this case, your code should look like this:

public function destroy($id)
    {
        $res = User::destroy($id);
        if ($res) {
            return response()->json([
                'status' => '1',
                'msg' => 'success'
            ]);
        } else {
            return response()->json([
                'status' => '0',
                'msg' => 'fail'
            ]);
        }
    }

More info about Laravel Eloquent Deleting Models

sed with literal string--not input file

You have a single quotes conflict, so use:

 echo "A,B,C" | sed "s/,/','/g"

If using , you can do too (<<< is a here-string):

sed "s/,/','/g" <<< "A,B,C"

but not

sed "s/,/','/g"  "A,B,C"

because sed expect file(s) as argument(s)

EDIT:

if you use or any other ones :

echo string | sed ...

JavaScript + Unicode regexes

Situation for ES 6

The upcoming ECMAScript language specification, edition 6, includes Unicode-aware regular expressions. Support must be enabled with the u modifier on the regex. See Unicode-aware regular expressions in ES6.

Until ES 6 is finished and widely adopted among browser vendors you're still on your own, though. Update: There is now a transpiler named regexpu that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. Try it out online.

Situation for ES 5 and below

Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.

How to use LocalBroadcastManager?

In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:

Android Tools -> Add Support Library

Once it was added, then I was able to use LocalBroadcastManager class in my code.


Android Compatibility Library

Setting the selected attribute on a select list using jQuery

<select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>

var make = "fiat";

$("#cars option[value='" + make + "']").attr("selected","selected");

Read a plain text file with php

W3Schools is your friend: http://www.w3schools.com/php/func_filesystem_fgets.asp

And here: http://php.net/manual/en/function.fopen.php has more info on fopen including what the modes are.

What W3Schools says:

<?php
$file = fopen("test.txt","r");

while(! feof($file))
  {
  echo fgets($file). "<br />";
  }

fclose($file);
?> 

fopen opens the file (in this case test.txt with mode 'r' which means read-only and places the pointer at the beginning of the file)

The while loop tests to check if it's at the end of file (feof) and while it isn't it calls fgets which gets the current line where the pointer is.

Continues doing this until it is the end of file, and then closes the file.

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

Telling Python to save a .txt file to a certain directory on Windows and Mac

A small update to this. raw_input() is renamed as input() in Python 3.

Python 3 release note

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.

For me it works if I just do a

db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));

using SimpleJDBCTemplate or JDBCTemplate

Simulating ENTER keypress in bash script

You could make use of expect (man expect comes with examples).

Naming conventions for Java methods that return boolean

The convention is to ask a question in the name.

Here are a few examples that can be found in the JDK:

isEmpty()

hasChildren()

That way, the names are read like they would have a question mark on the end.

Is the Collection empty?
Does this Node have children?

And, then, true means yes, and false means no.

Or, you could read it like an assertion:

The Collection is empty.
The node has children

Note:
Sometimes you may want to name a method something like createFreshSnapshot?. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.

In this case you should rethink what you are actually asking. Something like isSnapshotExpired is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.

If you do a Google Search for isEmpty() in the Java API, you get lots of results.

throwing an exception in objective-c/cocoa

You can use two methods for raising exception in the try catch block

@throw[NSException exceptionWithName];

or the second method

NSException e;
[e raise];

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

SOAP request to WebService with java

A SOAP request is an XML file consisting of the parameters you are sending to the server.

The SOAP response is equally an XML file, but now with everything the service wants to give you.

Basically the WSDL is a XML file that explains the structure of those two XML.


To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):

SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.

See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String args[]) {
        /*
            The example below requests from the Web Service at:
             http://www.webservicex.net/uszip.asmx?op=GetInfoByCity


            To call other WS, change the parameters below, which are:
             - the SOAP Endpoint URL (that is, where the service is responding from)
             - the SOAP Action

            Also change the contents of the method createSoapEnvelope() in this class. It constructs
             the inner part of the SOAP envelope that is actually sent.
         */
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

            /*
            Constructed SOAP Request Message:
            <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
                <SOAP-ENV:Header/>
                <SOAP-ENV:Body>
                    <myNamespace:GetInfoByCity>
                        <myNamespace:USCity>New York</myNamespace:USCity>
                    </myNamespace:GetInfoByCity>
                </SOAP-ENV:Body>
            </SOAP-ENV:Envelope>
            */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            // Create SOAP Connection
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            // Send SOAP Message to SOAP Server
            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            // Print the SOAP Response
            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        /* Print the request message, just for debugging purposes */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }

}

Using wget to recursively fetch a directory with arbitrary files in it

To fetch a directory recursively with username and password, use the following command:

wget -r --user=(put username here) --password='(put password here)' --no-parent http://example.com/

How to make a great R reproducible example

Please do not paste your console outputs like this:

If I have a matrix x as follows:
> x <- matrix(1:8, nrow=4, ncol=2,
            dimnames=list(c("A","B","C","D"), c("x","y")))
> x
  x y
A 1 5
B 2 6
C 3 7
D 4 8
>

How can I turn it into a dataframe with 8 rows, and three
columns named `row`, `col`, and `value`, which have the
dimension names as the values of `row` and `col`, like this:
> x.df
    row col value
1    A   x      1
...
(To which the answer might be:
> x.df <- reshape(data.frame(row=rownames(x), x), direction="long",
+                varying=list(colnames(x)), times=colnames(x),
+                v.names="value", timevar="col", idvar="row")
)

We can not copy-paste it directly.

To make questions and answers properly reproducible, try to remove + & > before posting it and put # for outputs and comments like this:

#If I have a matrix x as follows:
x <- matrix(1:8, nrow=4, ncol=2,
            dimnames=list(c("A","B","C","D"), c("x","y")))
x
#  x y
#A 1 5
#B 2 6
#C 3 7
#D 4 8

# How can I turn it into a dataframe with 8 rows, and three
# columns named `row`, `col`, and `value`, which have the
# dimension names as the values of `row` and `col`, like this:

#x.df
#    row col value
#1    A   x      1
#...
#To which the answer might be:

x.df <- reshape(data.frame(row=rownames(x), x), direction="long",
                varying=list(colnames(x)), times=colnames(x),
                v.names="value", timevar="col", idvar="row")

One more thing, if you have used any function from certain package, mention that library.

WPF: Setting the Width (and Height) as a Percentage Value

The way to stretch it to the same size as the parent container is to use the attribute:

 <Textbox HorizontalAlignment="Stretch" ...

That will make the Textbox element stretch horizontally and fill all the parent space horizontally (actually it depends on the parent panel you're using but should work for most cases).

Percentages can only be used with grid cell values so another option is to create a grid and put your textbox in one of the cells with the appropriate percentage.

append multiple values for one key in a dictionary

If you want a (almost) one-liner:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

Using dict.setdefault, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d.

This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

I'm pretty sure this isn't the BEST way, but you could set the MinimumSize and MaximimSize properties to the same value. That will stop it.

How to search for a string inside an array of strings

Extending the contains function you linked to:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    if(a[i].search(regex) > -1){
      return i;
    }
  }
  return -1;
}

Then you call the function with an array of strings and a regex, in your case to look for height:

containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)

You could additionally also return the index where height was found:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    int pos = a[i].search(regex);
    if(pos > -1){
      return [i, pos];
    }
  }
  return null;
}

How to create an XML document using XmlDocument?

What about:

#region Using Statements
using System;
using System.Xml;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XmlDocument doc = new XmlDocument( );

        //(1) the xml declaration is recommended, but not mandatory
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration( "1.0", "UTF-8", null );
        XmlElement root = doc.DocumentElement;
        doc.InsertBefore( xmlDeclaration, root );

        //(2) string.Empty makes cleaner code
        XmlElement element1 = doc.CreateElement( string.Empty, "body", string.Empty );
        doc.AppendChild( element1 );

        XmlElement element2 = doc.CreateElement( string.Empty, "level1", string.Empty );
        element1.AppendChild( element2 );

        XmlElement element3 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text1 = doc.CreateTextNode( "text" );
        element3.AppendChild( text1 );
        element2.AppendChild( element3 );

        XmlElement element4 = doc.CreateElement( string.Empty, "level2", string.Empty );
        XmlText text2 = doc.CreateTextNode( "other text" );
        element4.AppendChild( text2 );
        element2.AppendChild( element4 );

        doc.Save( "D:\\document.xml" );
    }
}

(1) Does a valid XML file require an xml declaration?
(2) What is the difference between String.Empty and “” (empty string)?


The result is:

<?xml version="1.0" encoding="UTF-8"?>
<body>
  <level1>
    <level2>text</level2>
    <level2>other text</level2>
  </level1>
</body>

But I recommend you to use LINQ to XML which is simpler and more readable like here:

#region Using Statements
using System;
using System.Xml.Linq;
#endregion 

class Program {
    static void Main( string[ ] args ) {
        XDocument doc = new XDocument( new XElement( "body", 
                                           new XElement( "level1", 
                                               new XElement( "level2", "text" ), 
                                               new XElement( "level2", "other text" ) ) ) );
        doc.Save( "D:\\document.xml" );
    }
}

Removing duplicate rows from table in Oracle

create table abcd(id number(10),name varchar2(20))

insert into abcd values(1,'abc')

insert into abcd values(2,'pqr')


insert into abcd values(3,'xyz')

insert into abcd values(1,'abc')

insert into abcd values(2,'pqr')

insert into abcd values(3,'xyz')


select * from abcd
id  Name
1   abc
2   pqr
3   xyz
1   abc
2   pqr
3   xyz

Delete Duplicate record but keep Distinct Record in table 

DELETE 
FROM abcd a
WHERE ROWID > (SELECT MIN(ROWID) FROM abcd b
WHERE b.id=a.id
);

run the above query 3 rows delete 

select * from abcd

id  Name 
1   abc
2   pqr
3   xyz

Detecting when the 'back' button is pressed on a navbar

First Method

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    if (![parent isEqual:self.parentViewController]) {
         NSLog(@"Back pressed");
    }
}

Second Method

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
       // back button was pressed.  We know this is true because self is no longer
       // in the navigation stack.  
    }
    [super viewWillDisappear:animated];
}

What are functional interfaces used for in Java 8?

As others have said, a functional interface is an interface which exposes one method. It may have more than one method, but all of the others must have a default implementation. The reason it's called a "functional interface" is because it effectively acts as a function. Since you can pass interfaces as parameters, it means that functions are now "first-class citizens" like in functional programming languages. This has many benefits, and you'll see them quite a lot when using the Stream API. Of course, lambda expressions are the main obvious use for them.

Dark color scheme for Eclipse

This is the best place for Eclipse color themes:

http://www.eclipsecolorthemes.org/

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

How update the _id of one MongoDB Document?

You can also create a new document from MongoDB compass or using command and set the specific _id value that you want.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

Here's a to-and-from for Roman numerals. Not often used, but could be handy. Usage:

if ("IV".IsValidRomanNumeral())
{
   // Do useful stuff with the number 4.
}

Console.WriteLine("MMMDCCCLXXXVIII".ParseRomanNumeral());
Console.WriteLine(3888.ToRomanNumeralString());

The source:

    public static class RomanNumeralExtensions
    {
        private const int NumberOfRomanNumeralMaps = 13;

        private static readonly Dictionary<string, int> romanNumerals =
            new Dictionary<string, int>(NumberOfRomanNumeralMaps)
            {
                { "M", 1000 }, 
                { "CM", 900 }, 
                { "D", 500 }, 
                { "CD", 400 }, 
                { "C", 100 }, 
                { "XC", 90 }, 
                { "L", 50 }, 
                { "XL", 40 }, 
                { "X", 10 }, 
                { "IX", 9 }, 
                { "V", 5 }, 
                { "IV", 4 }, 
                { "I", 1 }
            };

        private static readonly Regex validRomanNumeral = new Regex(
            "^(?i:(?=[MDCLXVI])((M{0,3})((C[DM])|(D?C{0,3}))"
            + "?((X[LC])|(L?XX{0,2})|L)?((I[VX])|(V?(II{0,2}))|V)?))$", 
            RegexOptions.Compiled);

        public static bool IsValidRomanNumeral(this string value)
        {
            return validRomanNumeral.IsMatch(value);
        }

        public static int ParseRomanNumeral(this string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            value = value.ToUpperInvariant().Trim();

            var length = value.Length;

            if ((length == 0) || !value.IsValidRomanNumeral())
            {
                throw new ArgumentException("Empty or invalid Roman numeral string.", "value");
            }

            var total = 0;
            var i = length;

            while (i > 0)
            {
                var digit = romanNumerals[value[--i].ToString()];

                if (i > 0)
                {
                    var previousDigit = romanNumerals[value[i - 1].ToString()];

                    if (previousDigit < digit)
                    {
                        digit -= previousDigit;
                        i--;
                    }
                }

                total += digit;
            }

            return total;
        }

        public static string ToRomanNumeralString(this int value)
        {
            const int MinValue = 1;
            const int MaxValue = 3999;

            if ((value < MinValue) || (value > MaxValue))
            {
                throw new ArgumentOutOfRangeException("value", value, "Argument out of Roman numeral range.");
            }

            const int MaxRomanNumeralLength = 15;
            var sb = new StringBuilder(MaxRomanNumeralLength);

            foreach (var pair in romanNumerals)
            {
                while (value / pair.Value > 0)
                {
                    sb.Append(pair.Key);
                    value -= pair.Value;
                }
            }

            return sb.ToString();
        }
    }

How to style CSS role

The shortest way to write a selector that accesses that specific div is to simply use

[role=main] {
  /* CSS goes here */
}

The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.

_x000D_
_x000D_
[role=main] {_x000D_
  background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
  <span role="main">Hello</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to delete the last row of data of a pandas dataframe

DF[:-n]

where n is the last number of rows to drop.

To drop the last row :

DF = DF[:-1]

What is the Linux equivalent to DOS pause?

read does this:

user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$ 

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

If you are using Bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
    echo 'A key was pressed.'
else
    echo 'No key was pressed.'
fi

The model backing the 'ApplicationDbContext' context has changed since the database was created

From the Tools menu, click NuGet Package Manger, then click Package Manager Console (PMC). Enter the following commands in the PMC.

Enable-Migrations Add-Migration Init Update-Database Run the application. The solution to the problem is from here

How to add element to C++ array?

Use a vector:

#include <vector>

void foo() {
    std::vector <int> v;
    v.push_back( 1 );       // equivalent to v[0] = 1
}

How to trim a file extension from a String in JavaScript?

Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';

    yourStr = yourStr.slice(0, -4); // 'test'

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Pandas every nth row

A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.

import pandas as pd
from csv import DictReader

def make_downsampled_df(filename, interval):    
    with open(filename, 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        column_names = csv_dict_reader.fieldnames
        df = pd.DataFrame(columns=column_names)
    
        for index, row in enumerate(csv_dict_reader):
            if index % interval == 0:
               print(str(row))
               df = df.append(row, ignore_index=True)

    return df

Invalid hook call. Hooks can only be called inside of the body of a function component

Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.

Laravel 5 – Clear Cache in Shared Hosting Server

Go to laravelFolder/bootstrap/cache then rename config.php to anything you want eg. config.php_old and reload your site. That should work like voodoo.

Convert Pandas Column to DateTime

Use the pandas to_datetime function to parse the column as DateTime. Also, by using infer_datetime_format=True, it will automatically detect the format and convert the mentioned column to DateTime.

import pandas as pd
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

How to link an image and target a new window

To open in a new tab use:

target = "_blank"

To open in the same tab use:

target = "_self"

How to multiply all integers inside list

#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
    results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.

print(results)

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Also In VS 2015 Community Edition

go to Debug->Options or Tools->Options

and check Debugging->General->Suppress JIT optimization on module load (Managed only)

How to loop through all but the last item of a list?

if you meant comparing nth item with n+1 th item in the list you could also do with

>>> for i in range(len(list[:-1])):
...     print list[i]>list[i+1]

note there is no hard coding going on there. This should be ok unless you feel otherwise.

Angular 2 Sibling Component Communication

I have been passing down setter methods from the parent to one of its children through a binding, calling that method with the data from the child component, meaning that the parent component is updated and can then update its second child component with the new data. It does require binding 'this' or using an arrow function though.

This has the benefit that the children aren't so coupled to each other as they don't need a specific shared service.

I am not entirely sure that this is best practice, would be interesting to hear others views on this.

JavaFX: How to get stage from controller during initialization?

You can get the instance of the controller from the FXMLLoader after initialization via getController(), but you need to instantiate an FXMLLoader instead of using the static methods then.

I'd pass the stage after calling load() directly to the controller afterwards:

FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do

Android - Share on Facebook, Twitter, Mail, ecc

String message = "This is testing."
Intent shareText = new Intent(Intent.ACTION_SEND);
shareText .setType("text/plain");
shareText .putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(shareText , "Title of the dialog the system will open"));

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

Standard concise way to copy a file in Java?

  • These methods are performance-engineered (they integrate with operating system native I/O).
  • These methods work with files, directories and links.
  • Each of the options supplied may be left out - they are optional.

The utility class

package com.yourcompany.nio;

class Files {

    static int copyRecursive(Path source, Path target, boolean prompt, CopyOptions options...) {
        CopyVisitor copyVisitor = new CopyVisitor(source, target, options).copy();
        EnumSet<FileVisitOption> fileVisitOpts;
        if (Arrays.toList(options).contains(java.nio.file.LinkOption.NOFOLLOW_LINKS) {
            fileVisitOpts = EnumSet.noneOf(FileVisitOption.class) 
        } else {
            fileVisitOpts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        }
        Files.walkFileTree(source[i], fileVisitOpts, Integer.MAX_VALUE, copyVisitor);
    }

    private class CopyVisitor implements FileVisitor<Path>  {
        final Path source;
        final Path target;
        final CopyOptions[] options;

        CopyVisitor(Path source, Path target, CopyOptions options...) {
             this.source = source;  this.target = target;  this.options = options;
        };

        @Override
        FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
        // before visiting entries in a directory we copy the directory
        // (okay if directory already exists).
        Path newdir = target.resolve(source.relativize(dir));
        try {
            Files.copy(dir, newdir, options);
        } catch (FileAlreadyExistsException x) {
            // ignore
        } catch (IOException x) {
            System.err.format("Unable to create: %s: %s%n", newdir, x);
            return SKIP_SUBTREE;
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        Path newfile= target.resolve(source.relativize(file));
        try {
            Files.copy(file, newfile, options);
        } catch (IOException x) {
            System.err.format("Unable to copy: %s: %s%n", source, x);
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
        // fix up modification time of directory when done
        if (exc == null && Arrays.toList(options).contains(COPY_ATTRIBUTES)) {
            Path newdir = target.resolve(source.relativize(dir));
            try {
                FileTime time = Files.getLastModifiedTime(dir);
                Files.setLastModifiedTime(newdir, time);
            } catch (IOException x) {
                System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
            }
        }
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        if (exc instanceof FileSystemLoopException) {
            System.err.println("cycle detected: " + file);
        } else {
            System.err.format("Unable to copy: %s: %s%n", file, exc);
        }
        return CONTINUE;
    }
}

Copying a directory or file

long bytes = java.nio.file.Files.copy( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES,
                 java.nio.file.LinkOption.NOFOLLOW_LINKS);

Moving a directory or file

long bytes = java.nio.file.Files.move( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.ATOMIC_MOVE,
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING);

Copying a directory or file recursively

long bytes = com.yourcompany.nio.Files.copyRecursive( 
                 new java.io.File("<filepath1>").toPath(), 
                 new java.io.File("<filepath2>").toPath(),
                 java.nio.file.StandardCopyOption.REPLACE_EXISTING,
                 java.nio.file.StandardCopyOption.COPY_ATTRIBUTES
                 java.nio.file.LinkOption.NOFOLLOW_LINKS );

How to filter JSON Data in JavaScript or jQuery?

You can use jQuery each function as it is explained below:

Define your data:

var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';

Parse JSON string to JSON object:

var json = JSON.parse(jsonStr);

Iterate and filter:

$.each(JSON.parse(json), function (idx, obj) {
    if (obj.website == 'yahoo') {
        // do whatever you want
    }
});

good postgresql client for windows?

do you mean something like pgAdmin for administration?

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

Dictionary returning a default value if the key does not exist

I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.

I wish this were just part of the base Dictionary class.

public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
  TValue _default;
  public TValue DefaultValue {
    get { return _default; }
    set { _default = value; }
  }
  public DictionaryWithDefault() : base() { }
  public DictionaryWithDefault(TValue defaultValue) : base() {
    _default = defaultValue;
  }
  public new TValue this[TKey key]
  {
    get { 
      TValue t;
      return base.TryGetValue(key, out t) ? t : _default;
    }
    set { base[key] = value; }
  }
}

Beware, however. By subclassing and using new (since override is not available on the native Dictionary type), if a DictionaryWithDefault object is upcast to a plain Dictionary, calling the indexer will use the base Dictionary implementation (throwing an exception if missing) rather than the subclass's implementation.

Replace \n with actual new line in Sublime Text

  1. Open Find and Replace Option ( CTRL + ALT + F in Mac )
  2. Type \n in find input box
  3. Click on Find All button, This will select all the \n in the text with the cursor
  4. Now press Enter, this will replace \n with the New Line

How to create a inset box-shadow only on one side?

try it, maybe useful...

box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 3px #cbc9c9;
                    -webkit-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -o-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -moz-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;  

above CSS cause you have a box shadow in bottom.
you can red more Here

Simple PHP form: Attachment to email (code golf)

Just for fun I thought I'd knock it up. It ended up being trickier than I thought because I went in not fully understanding how the boundary part works, eventually I worked out that the starting and ending '--' were significant and off it went.

<?php
    if(isset($_POST['submit']))
    {
        //The form has been submitted, prep a nice thank you message
        $output = '<h1>Thanks for your file and message!</h1>';
        //Set the form flag to no display (cheap way!)
        $flags = 'style="display:none;"';

        //Deal with the email
        $to = '[email protected]';
        $subject = 'a file for you';

        $message = strip_tags($_POST['message']);
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $_FILES['file']['name'];

        $boundary =md5(date('r', time())); 

        $headers = "From: [email protected]\r\nReply-To: [email protected]";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $message="This is a multi-part message in MIME format.

--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit

$message

--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

$attachment
--_1_$boundary--";

        mail($to, $subject, $message, $headers);
    }
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MailFile</title>
</head>

<body>

<?php echo $output; ?>

<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>>
<p><label for="message">Message</label> <textarea name="message" id="message" cols="20" rows="8"></textarea></p>
<p><label for="file">File</label> <input type="file" name="file" id="file"></p>
<p><input type="submit" name="submit" id="submit" value="send"></p>
</form>
</body>
</html>

Very barebones really, and obviously the using inline CSS to hide the form is a bit cheap and you'd almost certainly want a bit more feedback to the user! Also, I'd probably spend a bit more time working out what the actual Content-Type for the file is, rather than cheating and using application/octet-stream but that part is quite as interesting.

How to use an array list in Java?

You should read collections framework tutorial first of all.

But to answer your question this is how you should do it:

ArrayList<String> strings = new ArrayList<String>();
strings.add("String1");
strings.add("String2");

// To access a specific element:
System.out.println(strings.get(1));
// To loop through and print all of the elements:
for (String element : strings) {
    System.out.println(element);
}

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt
echo %COMPUTERNAME%

Taking the record with the max date

A is the key, max(date) is the value, we might simplify the query as below:

SELECT distinct A, max(date) over (partition by A)
  FROM TABLENAME

How do you make a div follow as you scroll?

You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)

.Fixed
{
    position: fixed;
    top: 20px;
}

or with jQuery:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').css('top', $(this).scrollTop());
});

Python csv string to array

Panda is quite powerful and smart library reading CSV in Python

A simple example here, I have example.zip file with four files in it.

EXAMPLE.zip
 -- example1.csv
 -- example1.txt
 -- example2.csv
 -- example2.txt

from zipfile import ZipFile
import pandas as pd


filepath = 'EXAMPLE.zip'
file_prefix = filepath[:-4].lower()

zipfile = ZipFile(filepath)
target_file = ''.join([file_prefix, '/', file_prefix, 1 , '.csv'])

df = pd.read_csv(zipfile.open(target_file))

print(df.head()) # print first five row of csv
print(df[COL_NAME]) # fetch the col_name data

Once you have data you can manipulate to play with a list or other formats.

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Get all unique values in a JavaScript array (remove duplicates)

This has been answered a lot, but it didn't address my particular need.

Many answers are like this:

a.filter((item, pos, self) => self.indexOf(item) === pos);

But this doesn't work for arrays of complex objects.

Say we have an array like this:

const a = [
 { age: 4, name: 'fluffy' },
 { age: 5, name: 'spot' },
 { age: 2, name: 'fluffy' },
 { age: 3, name: 'toby' },
];

If we want the objects with unique names, we should use array.prototype.findIndex instead of array.prototype.indexOf:

a.filter((item, pos, self) => self.findIndex(v => v.name === item.name) === pos);

php.ini & SMTP= - how do you pass username & password

I prefer the PHPMailer tool as it doesn't require PEAR. But either way, you have a misunderstanding: you don't want a PHP-server-wide setting for the SMTP user and password. This should be a per-app (or per-page) setting. If you want to use the same account across different PHP pages, add it to some kind of settings.php file.

How to deploy a Java Web Application (.war) on tomcat?

The tomcat manual says:

Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

Download File Using Javascript/jQuery

I have had good results with using a FORM tag since it works everywhere and you don't have to create temporarily files on server. The method works like this.

On the client side (page HTML) you create an invisible form like this

<form method="POST" action="/download.php" target="_blank" id="downloadForm">
    <input type="hidden" name="data" id="csv">
</form>

Then you add this Javascript code to your button:

$('#button').click(function() {
     $('#csv').val('---your data---');
     $('#downloadForm').submit();
}

The on the server-side you have the following PHP code in download.php:

<?php
header('Content-Type: text/csv');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=out.csv');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($data));

echo $_REQUEST['data'];
exit();

You can even create zip files of your data like this:

<?php

$file = tempnam("tmp", "zip");

$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$zip->addFromString('test.csv', $_REQUEST['data']);
$zip->close();

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file); 

The best part is it does not leave any residual files on your server since everything is created and destroyed on the fly!

How do you find the current user in a Windows environment?

I use this method in writing batch files for testing.

echo %userdomain%\%username%

Since you must include the password in plain text if authentication is required, I will only use it in a completely private environment where other users cannot view it or if a user seeing the password would bear no consequences.

Hope this helps someone out.

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

This works pretty well

var price=99.012334554
price = price.roundTodouble();
print(price); // 99.01

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Unclosed Character Literal error

I'd like to give a small addition to the existing answers. You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form. Like when you write:

char HI = '\3072';

You have to use the correct form which is:

char HI = '\u3072';

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

symfony 2 twig limit the length of the text and put three dots

@mshobnr / @olegkhuss solution made into a simple macro:

{% macro trunc(txt, len) -%}
    {{ txt|length > len ? txt|slice(0, len) ~ '…' : txt }}
{%- endmacro %}

Usage example:

{{ tools.trunc('This is the text to truncate. ', 50) }}

N.b. I import a Twig template containing macros and import it as 'tools' like this (Symfony):

{% import "@AppBundle/tools.html.twig" as tools -%}

Also, I replaced the html character code with the actual character, this should be no problem when using UTF-8 as the file encoding. This way you don't have to use |raw (as it could cause a security issue).

Generating an MD5 checksum of a file

I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:

I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit or /usr/bin/time result from each of several methods of checksumming a file of approx. 11MB:

$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f  /tmp/test.data.300k

real    0m0.043s
user    0m0.032s
sys     0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400

So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum function (md5sum_read in the above listing) is pretty similar to Omnifarious's:

import hashlib
def md5sum(filename, blocksize=65536):
    hash = hashlib.md5()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hash.update(block)
    return hash.hexdigest()

Granted, these are from single runs (the mmap ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize) after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum on the command line is not necessarily faster than a Python implementation...

EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32() call:

import zlib
def adler32sum(filename, blocksize=65536):
    checksum = zlib.adler32("")
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            checksum = zlib.adler32(block, checksum)
    return checksum & 0xffffffff

Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for "", which is 1 -- CRC can start with 0 instead. The AND-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.

What is the meaning of <> in mysql query?

<> means not equal to, != also means not equal to.

Documentation

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

What is the correct way to declare a boolean variable in Java?

In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.

This is helpful when your equals method call throws some exception e.g. NullPointerException;

     boolean isMatch = false;

     try{
         isMatch = email1.equals (email2);
      }catch(NullPointerException npe){
         .....
      }
      System.out.print("Match=="+isMatch);
      if(isMatch){
        ......
      }

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Selenium WebDriver can't find element by link text

A CSS selector approach could definitely work here. Try:

driver.findElement(By.CssSelector("a.item")).Click();

This will not work if there are other anchors before this one of the class item. You can better specify the exact element if you do something like "#my_table > a.item" where my_table is the id of a table that the anchor is a child of.

Do subclasses inherit private fields?

It would seem that a subclass does inherit the private fields in that these very fields are utilized in the inner workings of the subclass (philosophically speaking). A subclass, in its constructor, calls the superclass constructor. The superclass private fields are obviously inherited by the subclass calling the superclass constructor if the superclass constructor has initialized these fields in its constructor. That's just an example. But of course without accessor methods the subclass cannot access the superclass private fields (it's like not being able to pop the back panel of an iPhone to take the battery out to reset the phone... but the battery is still there).

PS One of the many definitions of inheritance that I have come across: "Inheritance -- a programming technique that allows a derived class to extend the functionality of a base class, inheriting all of its STATE (emphasis is mine) and behaviour."

The private fields, even if not accessible by the subclass, are the inherited state of the superclass.

Get current date, given a timezone in PHP?

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

Here's the short version:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php


Here's a version with an existing time and setting timezone by a user setting

<?php

$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');

Here is a more verbose version to show the process a little more clearly

<?php

// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');

// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');     

// Output line break (for testing)
echo "\n<br />\n";

// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';

// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);

// Output date after 
echo $date->format('l, F j Y g:i:s A');

Libraries

  • Carbon — A very popular date library.
  • Chronos — A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date — An extension of Carbon that adds multi-language support.

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.


Bonus Lesson: Immutable Date Objects

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

<?php

// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";

The output:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTime object in PHP not only returns the updated date but modifies the original object as well.

This is where DateTimeImmutable comes in.

$today = new DateTimeImmutable();

echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";

$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));

echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";

The output:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutable instead of DateTime, we prevent accidental state mutations and prevent potential bugs.

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

Laravel Migration table already exists, but I want to add new not the older

Answer is very straight forward :

First take a backup of folder bootstrap/cache.

Then delete all the files from bootstrap/cache folder .

Now run:

php artisan migrate 

What is Common Gateway Interface (CGI)?

A CGI script is a console/shell program. In Windows, when you use a "Command Prompt" window, you execute console programs. When a web server executes a CGI script it provides input to the console/shell program using environment variables or "standard input". Standard input is like typing data into a console/shell program; in the case of a CGI script, the web server does the typing. The CGI script writes data out to "standard output" and that output is sent to the client (the web browser) as a HTML page. Standard output is like the output you see in a console/shell program except the web server reads it and sends it out.

A CGI script can be executed from a browser. The URI typically includes a query string that is provided to the CGI script. If the method is "get" then the query string is provided to the CGI Script in an environment variable called QUERY_STRING. If the method is "post" then the query string is provided to the CGI Script using standard input (the CGI Script reads the query string from standard input).

An early use of CGI scripts was to process forms. In the beginning of HTML, HTML forms typically had an "action" attribute and a button designated as the "submit" button. When the submit button is pushed the URI specified in the "action" attribute would be sent to the server with the data from the form sent as a query string. If the "action" specifies a CGI script then the CGI script would be executed and it then produces a HTML page.

RFC 3875 "The Common Gateway Interface (CGI)" partially defines CGI using C, as in saying that environment variables "are accessed by the C library routine getenv() or variable environ".

If you are developing a CGI script using C/C++ and use Microsoft Visual Studio to do that then you would develop a console program.

How to create a numeric vector of zero length in R

Simply:

x <- vector(mode="numeric", length=0)

How do I output text without a newline in PowerShell?

You simply cannot get PowerShell to omit those pesky newlines... There is no script or cmdlet that does. Of course, Write-Host is absolute nonsense, because you can't redirect/pipe from it!

Nevertheless, you can write your own EXE file to do it which is what I explained how to do in Stack Overflow question How to output something in PowerShell.

What's the difference between "static" and "static inline" function?

By default, an inline definition is only valid in the current translation unit.

If the storage class is extern, the identifier has external linkage and the inline definition also provides the external definition.

If the storage class is static, the identifier has internal linkage and the inline definition is invisible in other translation units.

If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.

As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static and static inline function definitions.

The inline specifier (like the register storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.

inline and register are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register-qualified variables.

Personally, I use the convention to mark static function definitions within headers also inline, as the main reason for putting function definitions in header files is to make them inlinable.

In general, I only use static inline function and static const object definitions in addition to extern declarations within headers.

I've never written an inline function with a storage class different from static.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

What to do if i have to processed even more that 500000 records ?

There are a few ways, to increase the java heap size for your app where a few have suggested already. Your app need to remove the elements from your adddressMap as your app add new element into it and so you won't encounter oom if there are more records coming in. Look for producer-consumer if you are interested.

.war vs .ear file

Ear files provide more options to configure the interaction with the application server.

For example: if the hibernate version of the application server is older than the one provided by your dependencies, you can add the following to ear-deployer-jboss-beans.xml for JBOSS to isolate classloaders and avoid conflicts:

<bean name="EARClassLoaderDeployer" class="org.jboss.deployment.EarClassLoaderDeployer">    
  <property name="isolated">true</property>
</bean>

or to src/main/application/META-INF/jboss-app.xml :

<?xml version="1.0"?>
<jboss-app>
<loader-repository>
    loader=nameofyourear.ear
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</jboss-app> 

This will make sure that there is no classloader conflict between your application and the application server.

Normally the classloader mechanism works like this:

When a class loading request is presented to a class loader, it first asks its parent class loader to fulfill the request. The parent, in turn, asks its parent for the class until the request reaches the top of the hierarchy. If the class loader at the top of the hierarchy cannot fulfill the request, then the child class loader that called it is responsible for loading the class.

By isolating the classloaders, your ear classloader will not look in the parent (=JBoss / other AS classloader). As far is I know, this is not possible with war files.

Making the main scrollbar always visible

body { 
    min-height: 101vh; 
} 

works the best for me

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

Staging Deleted files

to Add all ready deleted files

git status -s | grep -E '^ D' | cut -d ' ' -f3 | xargs git add --all

thank check to make sure

git status

you should be good to go

Find if variable is divisible by 2

Use modulus:

// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0  

Simple division in Java - is this a bug or a feature?

In my case I was doing this:

double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));

Instead of the "correct" :

double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);

Take attention with the parentheses !

Counter inside xsl:for-each loop

Try:

<xsl:value-of select="count(preceding-sibling::*) + 1" />

Edit - had a brain freeze there, position() is more straightforward!

Get Context in a Service

Service extends ContextWrapper which extends Context. Hence the Service is a Context. Use 'this' keyword in the service.

How to get only the date value from a Windows Forms DateTimePicker control?

I'm assuming you mean a datetime picker in a winforms application.

in your code, you can do the following:

string theDate = dateTimePicker1.Value.ToShortDateString();

or, if you'd like to specify the format of the date:

string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

Why is semicolon allowed in this python snippet?

Python does not require semi-colons to terminate statements. Semi colons can be used to delimit statements if you wish to put multiple statements on the same line.

Now, why is this allowed? It's a simple design decision. I don't think Python needs this semi-colon thing, but somebody thought it would be nice to have and added it to the language.

Are static methods inherited in Java?

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

bypass invalid SSL certificate in .net core

I solve with this:

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            }
        });

YourService.cs

public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
        _clientFactory = clientFactory;
    }

var request = new HttpRequestMessage(...

var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");

HttpResponseMessage response = await client.SendAsync(request);

Retrieving parameters from a URL

Btw, I was having issues using parse_qs() and getting empty value parameters and learned that you have to pass a second optional parameter 'keep_blank_values' to return a list of the parameters in a query string that contain no values. It defaults to false. Some crappy written APIs require parameters to be present even if they contain no values

for k,v in urlparse.parse_qs(p.query, True).items():
  print k

Extract substring from a string

substring():

str.substring(startIndex, endIndex); 

How do I escape a string inside JavaScript code inside an onClick handler?

Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.

Changing permissions via chmod at runtime errors with "Operation not permitted"

In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.

Angular2 - Input Field To Accept Only Numbers

A modern approach for the best answer (without deprecated e.keyCode):

@HostListener('keydown', ['$event']) onKeyDown(event) {
    let e = <KeyboardEvent> event;
    if (['Delete', 'Backspace', 'Tab', 'Escape', 'Enter', 'NumLock', 'ArrowLeft', 'ArrowRight', 'End', 'Home', '.'].indexOf(e.key) !== -1 ||
      // Allow: Ctrl+A
      (e.key === 'a' && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+C
      (e.key === 'c' && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+V
      (e.key === 'v' && (e.ctrlKey || e.metaKey)) ||
      // Allow: Ctrl+X
      (e.key === 'x' && (e.ctrlKey || e.metaKey))) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].indexOf(e.key) === -1)) {
      e.preventDefault();
    }
}

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

Datatables Select All Checkbox

I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo

HTML:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
                <i class="far fa-square"></i>  
                </button>
            </th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td></td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>$170,750</td>
        </tr>
        <tr>
            <td></td>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>$86,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td></td>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td></td>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>$372,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>$137,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td></td>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td></td>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>30</td>
            <td>$90,560</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Javascript:

$(document).ready(function() {
    let myTable = $('#example').DataTable({
        columnDefs: [{
            orderable: false,
            className: 'select-checkbox',
            targets: 0,
        }],
        select: {
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'
            selector: 'td:first-child',
        },
        order: [
            [1, 'asc'],
        ],
    });

    $('#MyTableCheckAllButton').click(function() {
        if (myTable.rows({
                selected: true
            }).count() > 0) {
            myTable.rows().deselect();
            return;
        }

        myTable.rows().select();
    });

    myTable.on('select deselect', function(e, dt, type, indexes) {
        if (type === 'row') {
            // We may use dt instead of myTable to have the freshest data.
            if (dt.rows().count() === dt.rows({
                    selected: true
                }).count()) {
                // Deselect all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
                return;
            }

            if (dt.rows({
                    selected: true
                }).count() === 0) {
                // Select all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-square');
                return;
            }

            // Deselect some items button.
            $('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
        }
    });
});

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

The smallest difference between 2 Angles

Arithmetical (as opposed to algorithmic) solution:

angle = Pi - abs(abs(a1 - a2) - Pi);

referenced before assignment error in python

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

Because doA() does not modify the global total the output is 1 not 11.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    if (xml.StartsWith(_byteOrderMarkUtf8))
    {
        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
        xml = xml.Remove(0, lastIndexOfUtf8);
    }

Truncate a SQLite table if it exists?

"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...

example :

private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";


public void reset_table(String table_name){
    open_db();

    mydb.execSQL("Delete from "+table_name);
    mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");

    close_db();
}

public void open_db(){

    mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){

    mydb.close();
}

WPF: Grid with column/row margin/padding?

in uwp (Windows10FallCreatorsUpdate version and above)

<Grid RowSpacing="3" ColumnSpacing="3">

How to return temporary table from stored procedure

Take a look at this code,

CREATE PROCEDURE Test

AS
    DECLARE @tab table (no int, name varchar(30))

    insert @tab  select eno,ename from emp  

    select * from @tab
RETURN

Add column to SQL Server

Use this query:

ALTER TABLE tablename ADD columname DATATYPE(size);

And here is an example:

ALTER TABLE Customer ADD LastName VARCHAR(50);

Package opencv was not found in the pkg-config search path

When you run cmake add the additional parameter -D OPENCV_GENERATE_PKGCONFIG=YES (this will generate opencv.pc file)

Then make and sudo make install as before.

Use the name opencv4 instead of just opencv Eg:-

pkg-config --modversion opencv4

HTML input file selection event not firing upon selecting the same file

handleChange({target}) {
    const files = target.files
    target.value = ''
}

Easiest way to read/write a file's content in Python

with open('x.py') as f: s = f.read()

***grins***

base64 encode in MySQL

create table encrypt(username varchar(20),password varbinary(200))

insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';

How to read files from resources folder in Scala?

Resources in Scala work exactly as they do in Java. It is best to follow the Java best practices and put all resources in src/main/resources and src/test/resources.

Example folder structure:

testing_styles/
+-- build.sbt
+-- src
¦   +-- main
¦       +-- resources
¦       ¦   +-- readme.txt

Scala 2.12.x && 2.13.x reading a resource

To read resources the object Source provides the method fromResource.

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines

reading resources prior 2.12 (still my favourite due to jar compatibility)

To read resources you can use getClass.getResource and getClass.getResourceAsStream .

val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines

nicer error feedback (2.12.x && 2.13.x)

To avoid undebuggable Java NPEs, consider:

import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException

object Example {

  def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] = 
    Try(Source.fromResource(resourcePath).getLines)
      .recover(throw new FileNotFoundException(resourcePath))
 }

good to know

Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.

in Production

In production code I suggest to make sure that the source is closed again.