Programs & Examples On #Datacontract

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. A data contract precisely defines, for each parameter or return type, what data is serialized to be exchanged.

When to use DataContract and DataMember attributes?

Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff

Namespace for [DataContract]

DataContractAttribute Class is in the System.Runtime.Serialization namespace.

You should add a reference to System.Runtime.Serialization.dll. That assembly isn't referenced by default though. To add the reference to your project you have to go to References -> Add Reference in the Solution Explorer and add an assembly reference manually.

SQL to Query text in access with an apostrophe in it

Escape the apostrophe in O'Neal by writing O''Neal (two apostrophes).

MultipartException: Current request is not a multipart request

It looks like the problem is request to server is not a multi-part request. Basically you need to modify your client-side form. For example:

<form action="..." method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

Hope this helps.

How do I change the default library path for R packages

Windows 10 on a Network

Having your packages stored on the network drive can slow down the performance of R / R Studio considerably, and you spend a lot of time waiting for the libraries to load/install, due to the bottlenecks of having to retrieve and push data over the server back to your local host. See the following for instructions on how to create an .RProfile on your local machine:

  1. Create a directory called C:\Users\xxxxxx\Documents\R\3.4 (or whatever R version you are using, and where you will store your local R packages- your directory location may be different than mine)
  2. On R Console, type Sys.getenv("HOME") to get your home directory (this is where your .RProfile will be stored and R will always check there for packages- and this is on the network if packages are stored there)
  3. Create a file called .Rprofile and place it in :\YOUR\HOME\DIRECTORY\ON_NETWORK (the directory you get after typing Sys.getenv("HOME") in R Console)
  4. File contents of .Rprofile should be like this:

#search 2 places for packages- install new packages to first directory- load built-in packages from the second (this is from your base R package- will be different for some)

.libPaths(c("C:\Users\xxxxxx\Documents\R\3.4", "C:/Program Files/Microsoft/R Client/R_SERVER/library"))

message("*** Setting libPath to local hard drive ***")

#insert a sleep command at line 12 of the unpackPkgZip function. So, just after the package is unzipped.

trace(utils:::unpackPkgZip, quote(Sys.sleep(2)), at=12L, print=TRUE)

message("*** Add 2 second delay when installing packages, to accommodate virus scanner for R 3.4 (fixed in R 3.5+)***")

# fix problem with tcltk for sqldf package: https://github.com/ggrothendieck/sqldf#problem-involvling-tcltk

options(gsubfn.engine = "R")

message("*** Successfully loaded .Rprofile ***")
  1. Restart R Studio and verify that you see that the messages above are displayed.

Now you can enjoy faster performance of your application on local host, vs. storing the packages on the network and slowing everything down.

Best way to find the intersection of multiple sets?

Clearly set.intersection is what you want here, but in case you ever need a generalisation of "take the sum of all these", "take the product of all these", "take the xor of all these", what you are looking for is the reduce function:

from operator import and_
from functools import reduce
print(reduce(and_, [{1,2,3},{2,3,4},{3,4,5}])) # = {3}

or

print(reduce((lambda x,y: x&y), [{1,2,3},{2,3,4},{3,4,5}])) # = {3}

Replace negative values in an numpy array

Another minimalist Python solution without using numpy:

[0 if i < 0 else i for i in a]

No need to define any extra functions.

a = [1, 2, 3, -4, -5.23, 6]
[0 if i < 0 else i for i in a]

yields:

[1, 2, 3, 0, 0, 6]

How to convert a file into a dictionary?

IMHO a bit more pythonic to use generators (probably you need 2.7+ for this):

with open('infile.txt') as fd:
    pairs = (line.split(None) for line in fd)
    res   = {int(pair[0]):pair[1] for pair in pairs if len(pair) == 2 and pair[0].isdigit()}

This will also filter out lines not starting with an integer or not containing exactly two items

Cmake is not able to find Python-libraries

You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")

If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

Catching multiple exception types in one catch block

A great way is to use set_exception_handler.

Warning!!! with PHP 7, you might get a white screen of death for fatal errors. For example, if you call a method on a non-object you would normally get Fatal error: Call to a member function your_method() on null and you would expect to see this if error reporting is on.

The above error will NOT be caught with catch(Exception $e). The above error will NOT trigger any custom error handler set by set_error_handler.

You must use catch(Error $e){ } to catch errors in PHP7. . This could help:

class ErrorHandler{
    public static function excep_handler($e)
    {
        print_r($e);
    }
}
set_exception_handler(array('ErrorHandler','excep_handler'));

Passing arrays as url parameter

This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.

I will repeat this bit

$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);

Obviously you would format it better than this www.someurl.com?x=$query

And to get the data back

parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];

static files with express.js

npm install serve-index

var express    = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))

// Listen
app.listen(port,  function () {
  console.log('listening on port:',+ port );
})

onchange event for html.dropdownlist

If you have a list view you can do this:

  1. Define a select list:

    @{
       var Acciones = new SelectList(new[]
       {
      new SelectListItem { Text = "Modificar", Value = 
       Url.Action("Edit", "Countries")},
      new SelectListItem { Text = "Detallar", Value = 
      Url.Action("Details", "Countries") },
      new SelectListItem { Text = "Eliminar", Value = 
      Url.Action("Delete", "Countries") },
     }, "Value", "Text");
    }
    
  2. Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):

    @Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id = 
    item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
    
  3. onchange function can be something as:

    @section Scripts {
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    
    <script type="text/javascript">
    
    function RealizarAccion(accion, country)
    {
    
        var url = accion + '/' + country;
        if (url != null && url != '') {
            window.location.href = url ;
        }
    }
    </script>
    
    @Scripts.Render("~/bundles/jqueryval")
    }
    

Combining C++ and C - how does #ifdef __cplusplus work?

It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.

Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.

While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.

People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.

How to implement linear interpolation?

As I understand your question, you want to write some function y = interpolate(x_values, y_values, x), which will give you the y value at some x? The basic idea then follows these steps:

  1. Find the indices of the values in x_values which define an interval containing x. For instance, for x=3 with your example lists, the containing interval would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2
  2. Calculate the slope on this interval by (y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1]) (ie dy/dx).
  3. The value at x is now the value at x1 plus the slope multiplied by the distance from x1.

You will additionally need to decide what happens if x is outside the interval of x_values, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.

Did this help, or did you need more specific advice?

Clearing NSUserDefaults

Here is the answer in Swift:

let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

Convert Date/Time for given Timezone - java

As always, I recommend reading this article about date and time in Java so that you understand it.

The basic idea is that 'under the hood' everything is done in UTC milliseconds since the epoch. This means it is easiest if you operate without using time zones at all, with the exception of String formatting for the user.

Therefore I would skip most of the steps you have suggested.

  1. Set the time on an object (Date, Calendar etc).
  2. Set the time zone on a formatter object.
  3. Return a String from the formatter.

Alternatively, you can use Joda time. I have heard it is a much more intuitive datetime API.

Problems with local variable scope. How to solve it?

You have a scope problem indeed, because statement is a local method variable defined here:

protected void createContents() {
    ...
    Statement statement = null; // local variable
    ...
     btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
        @Override
        public void mouseDown(MouseEvent e) {
            ...
            try {
                statement.executeUpdate(query); // local variable out of scope here
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            ...
    });
}

When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable.

Sources:


How to solve it?

You could...

Make statement a class member instead of a local variable:

public class A1 { // Note Java Code Convention, also class name should be meaningful   
    private Statement statement;
    ...
}

You could...

Define another final variable and use this one instead, as suggested by @HotLicks:

protected void createContents() {
    ...
    Statement statement = null;
    try {
        statement = connect.createStatement();
        final Statement innerStatement = statement;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ...
}

But you should...

Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:

btnInsert.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseDown(MouseEvent e) {
       try {
           Class.forName("com.mysql.jdbc.Driver");
           try (Connection connect = DriverManager.getConnection(...);
                Statement statement = connect.createStatement()) {

                // execute the statement here

           } catch (SQLException ex) {
               ex.printStackTrace();
           }

       } catch (ClassNotFoundException ex) {
           e.printStackTrace();
       }
});

How to convert a Bitmap to Drawable in android?

covert bit map to drawable in sketchware app using code

    android.graphics.drawable.BitmapDrawable d = new android.graphics.drawable.BitmapDrawable(getResources(), bitmap);

C non-blocking keyboard input

There is no portable way to do this, but select() might be a good way. See http://c-faq.com/osdep/readavail.html for more possible solutions.

Update multiple rows in same query using PostgreSQL

Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :

drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;

select * from results_dummy;

-- THE update of multiple rows with/by different values
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;

select * from results_dummy;

-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set    status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;

Python constructor and default value

class Node:
    def __init__(self, wordList=None adjacencyList=None):
        self.wordList = wordList or []
        self.adjacencyList = adjacencyList or []

How do I generate a list with a specified increment step?

Executing seq(1, 10, 1) does what 1:10 does. You can change the last parameter of seq, i.e. by, to be the step of whatever size you like.

> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability 
> [1]  0  2  4  6  8 10

Call a global variable inside module

If You want to have a reference to this variable across the whole project, create somewhere d.ts file, e.g. globals.d.ts. Fill it with your global variables declarations, e.g.:

declare const BootBox: 'boot' | 'box';

Now you can reference it anywhere across the project, just like that:

const bootbox = BootBox;

Here's an example.

Using setattr() in python

To add to the other answers, a common use case I have found for setattr() is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:

configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }

If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:

MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...

However, it is much easier and less verbose to loop over the configs, and setattr() like so:

for name, val in configs.items():
    setattr(MyClass, name, val)

As long as your dictionary keys have the proper names, this works very well and is nice and tidy.

*Note, the dict keys need to be strings as they will be the class object names.

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

Read SQL Table into C# DataTable

var table = new DataTable();    
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{      
    da.Fill(table);
}

Combine a list of data frames into one data frame by row

There is also bind_rows(x, ...) in dplyr.

> system.time({ df.Base <- do.call("rbind", listOfDataFrames) })
   user  system elapsed 
   0.08    0.00    0.07 
> 
> system.time({ df.dplyr <- as.data.frame(bind_rows(listOfDataFrames)) })
   user  system elapsed 
   0.01    0.00    0.02 
> 
> identical(df.Base, df.dplyr)
[1] TRUE

Javascript: Load an Image from url and display

Add a div with ID imgDiv and make your script

 document.getElementById('imgDiv').innerHTML='<img src=\'http://webpage.com/images/'+document.getElementById('imagename').value +'.png\'>'

I tried to stay as close to your original as tp not overwhelm you with jQuery and such

Multiple submit buttons on HTML form – designate one button as default

You should not be using buttons of the same name. It's bad semantics. Instead, you should modify your backend to look for different name values being set:

<input type="submit" name="COMMAND_PREV" value="&lsaquo; Prev">
<input type="submit" name="COMMAND_SAVE" value="Save">
<input type="reset"  name="NOTHING" value="Reset">
<input type="submit" name="COMMAND_NEXT" value="Next &rsaquo;">
<input type="button" name="NOTHING" value="Skip &rsaquo;" onclick="window.location = 'yada-yada.asp';">

Since I don't know what language you are using on the backend, I'll give you some pseudocode:

if (input name COMMAND_PREV is set) {

} else if (input name COMMAND_SAVE is set) {

} else if (input name COMMENT_NEXT is set) {

}

JSON - Iterate through JSONArray

You could try my (*heavily borrowed from various sites) recursive method to go through all JSON objects and JSON arrays until you find JSON elements. This example actually searches for a particular key and returns all values for all instances of that key. 'searchKey' is the key you are looking for.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

Convert String to int array in java

It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:

    String arr = "[1,2]";

    JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");

    int[] outArr = new int[jsonArray.length()]; 

    for(int i=0; i<jsonArray.length(); i++) {
        outArr[i] = jsonArray.getInt(i);
    }

How to convert milliseconds into a readable date?

This is a solution. Later you can split by ":" and take the values of the array

 /**
 * Converts milliseconds to human readeable language separated by ":"
 * Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
 */
function dhm(t){
    var cd = 24 * 60 * 60 * 1000,
        ch = 60 * 60 * 1000,
        d = Math.floor(t / cd),
        h = '0' + Math.floor( (t - d * cd) / ch),
        m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
    return [d, h.substr(-2), m.substr(-2)].join(':');
}

//Example
var delay = 190980000;                   
var fullTime = dhm(delay);
console.log(fullTime);

Excel VBA function to print an array to the workbook

My tested version

Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)

Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)

End Sub

How can I generate a list of files with their absolute path in Linux?

Here's an example that prints out a list without an extra period and that also demonstrates how to search for a file match. Hope this helps:

find . -type f -name "extr*" -exec echo `pwd`/{} \; | sed "s|\./||"

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

The single * means that there can be any number of extra positional arguments. foo() can be invoked like foo(1,2,3,4,5). In the body of foo() param2 is a sequence containing 2-5.

The double ** means there can be any number of extra named parameters. bar() can be invoked like bar(1, a=2, b=3). In the body of bar() param2 is a dictionary containing {'a':2, 'b':3 }

With the following code:

def foo(param1, *param2):
    print(param1)
    print(param2)

def bar(param1, **param2):
    print(param1)
    print(param2)

foo(1,2,3,4,5)
bar(1,a=2,b=3)

the output is

1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}

Python Timezone conversion

# Program
import time
import os

os.environ['TZ'] = 'US/Eastern'
time.tzset()
print('US/Eastern in string form:',time.asctime()) 

os.environ['TZ'] = 'Australia/Melbourne'
time.tzset()
print('Australia/Melbourne in string form:',time.asctime())

os.environ['TZ'] = 'Asia/Kolkata'
time.tzset()
print('Asia/Kolkata in string form:',time.asctime()) 

Difference between MEAN.js and MEAN.io

I'm surprised nobody has mentioned the Yeoman generator angular-fullstack. It is the number one Yeoman community generator, with currently 1490 stars on the generator page vs Mean.js' 81 stars (admittedly not a fair comparison given how new MEANJS is). It is appears to be actively maintained and is in version 2.05 as I write this. Unlike MEANJS, it doesn't use Swig for templating. It can be scaffolded with passport built in.

Given final block not properly padded

I met this issue due to operation system, simple to different platform about JRE implementation.

new SecureRandom(key.getBytes())

will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);

"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.

View contents of database file in Android Studio

Finally, Android Studio supports this functionality with database inspector tab. You can apply view/update/query operations easily. It's not in stable channel for now but you can try out with the Android Studio 4.1 Canary 5 and higher.

You can see what the database inspector looks like here

And you can download appropriate version here

Error handling in getJSON calls

_x000D_
_x000D_
$.getJSON("example.json", function() {_x000D_
  alert("success");_x000D_
})_x000D_
.success(function() { alert("second success"); })_x000D_
.error(function() { alert("error"); })
_x000D_
_x000D_
_x000D_

It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback

Get a DataTable Columns DataType

if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")

PHP Foreach Arrays and objects

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

How can I connect to MySQL in Python 3 on Windows?

On my mac os maverick i try this:

After that, enter in the python3 interpreter and type:

  1. import pymysql. If there is no error your installation is ok. For verification write a script to connect to mysql with this form:

  2. # a simple script for MySQL connection import pymysql db = pymysql.connect(host="localhost", user="root", passwd="*", db="biblioteca") #Sure, this is information for my db # close the connection db.close ()*

Give it a name ("con.py" for example) and save it on desktop. In Terminal type "cd desktop" and then $python con.py If there is no error, you are connected with MySQL server. Good luck!

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

JSON Invalid UTF-8 middle byte

On the off chance it may help others I'll share a related anecdote.

I encountered this exact error (Invalid UTF-8 middle byte 0x3f) running a PowerShell script via the PowerShell Integrated Script Environment (ISE). The identical script, executed outside the ISE, works fine. The code uses the Confluence v3 and v5.x REST APIs and this error is logged on the Confluence v5.x server - presumably because the ISE somehow mucks with the request.

How to enable cURL in PHP / XAMPP

check if curl module is available

$ ls -la /etc/php5/mods-available/

enable the curl module

$ sudo php5enmod curl

source: http://baligena.com/installing-curl-ubuntu-server/

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

How to fix Cannot find module 'typescript' in Angular 4?

I had a very similar problem after moving a working project to a new subdirectory on my file system. It turned out I had failed to move the file named .angular-cli.json to the subfolder along with everything else. After noticing that and moving the file into the subdirectory, all was back to normal.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.

public static void testCharset(String fileName) {
    SortedMap<String, Charset> charsets = Charset.availableCharsets();
    for (String k : charsets.keySet()) {
        int line = 0;
        boolean success = true;
        try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
            while (b.ready()) {
                b.readLine();
                line++;
            }
        } catch (IOException e) {
            success = false;
            System.out.println(k+" failed on line "+line);
        }
        if (success) 
            System.out.println("*************************  Successs "+k);
    }
}

Round up value to nearest whole number in SQL UPDATE

Ceiling is the command you want to use.

Unlike Round, Ceiling only takes one parameter (the value you wish to round up), therefore if you want to round to a decimal place, you will need to multiply the number by that many decimal places first and divide afterwards.

Example.

I want to round up 1.2345 to 2 decimal places.

CEILING(1.2345*100)/100 AS Cost

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

json call with C#

just continuing what @Mulki made with his code

public string WebRequestinJson(string url, string postData)
{
    string ret = string.Empty;

    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }

    HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
    Stream resStream = resp.GetResponseStream();
    StreamReader reader = new StreamReader(resStream);
    ret = reader.ReadToEnd();

    return ret;
}

Open file dialog box in JavaScript

May use

$('<input type="file" />').click()

Virtualenv Command Not Found

You said that every time you run the pip install you get Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages. What you need to do is the following:

  1. Change Directory (go to to the one where the virtualenv.py) cd /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
  2. If you do an ls you will see that the script is there virtualenv.py
  3. Run the script like this: python virtualenv.py --distribute /the/path/at/which/you/want/the/new/venv/at theNameOfTheNewVirtualEnv

Hope this helps. My advice would be to research venvs more. Here is a good resource: https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/

SQL error "ORA-01722: invalid number"

An ORA-01722 error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a number.

Without seeing your table definition, it looks like you're trying to convert the numeric sequence at the end of your values list to a number, and the spaces that delimit it are throwing this error. But based on the information you've given us, it could be happening on any field (other than the first one).

How to check whether Kafka Server is running?

For Linux, "ps aux | grep kafka" see if kafka properties are shown in the results. E.g. /path/to/kafka/server.properties

What is the difference between a JavaBean and a POJO?

You've seen the formal definitions above, for all they are worth.

But don't get too hung up on definitions. Let's just look more at the sense of things here.

JavaBeans are used in Enterprise Java applications, where users frequently access data and/or application code remotely, i.e. from a server (via web or private network) via a network. The data involved must therefore be streamed in serial format into or out of the users' computers - hence the need for Java EE objects to implement the interface Serializable. This much of a JavaBean's nature is no different to Java SE application objects whose data is read in from, or written out to, a file system. Using Java classes reliably over a network from a range of user machine/OS combinations also demands the adoption of conventions for their handling. Hence the requirement for implementing these classes as public, with private attributes, a no-argument constructor and standardised getters and setters.

Java EE applications will also use classes other than those that were implemented as JavaBeans. These could be used in processing input data or organizing output data but will not be used for objects transferred over a network. Hence the above considerations need not be applied to them bar that the be valid as Java objects. These latter classes are referred to as POJOs - Plain Old Java Objects.

All in all, you could see Java Beans as just Java objects adapted for use over a network.

There's an awful lot of hype - and no small amount of humbug - in the software world since 1995.

How can I use JavaScript in Java?

You can use ScriptEngine, example:


public class Main {
    public static void main(String[] args) {
        StringBuffer javascript = null;
        ScriptEngine runtime = null;

        try {
            runtime = new ScriptEngineManager().getEngineByName("javascript");
            javascript = new StringBuffer();

            javascript.append("1 + 1");

            double result = (Double) runtime.eval(javascript.toString());

            System.out.println("Result: " + result);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

CSS – why doesn’t percentage height work?

Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified. (Using your example) Placing the second div inside the first div, would have rendered a result...example below...

<div id="working">
  <div id="not-working"></div>
</div>

The second div would be 30% of the first div's height.

How to Call a JS function using OnClick event

Using the onclick attribute or applying a function to your JS onclick properties will erase your onclick initialization in <head>.

What you need to do is add click events on your button. To do that you’ll need the addEventListener or attachEvent (IE) method.

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

javascript - Create Simple Dynamic Array

I had a similar problem and a solution I found (forgot where I found it) is this:

Array.from(Array(mynumber), (val, index) => index + 1)

Set background image according to screen resolution

Put into css file:

html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } 

URL images/bg.jpg is your background image

Scraping html tables into R data frames using the XML package

…or a shorter try:

library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

the picked table is the longest one on the page

tables[[which.max(n.rows)]]

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

What is an efficient way to implement a singleton pattern in Java?

Following are three different approaches

  1. Enum

     /**
     * Singleton pattern example using Java Enum
     */
     public enum EasySingleton {
         INSTANCE;
     }
    
  2. Double checked locking / lazy loading

     /**
     * Singleton pattern example with Double checked Locking
     */
     public class DoubleCheckedLockingSingleton {
          private static volatile DoubleCheckedLockingSingleton INSTANCE;
    
          private DoubleCheckedLockingSingleton() {}
    
          public static DoubleCheckedLockingSingleton getInstance() {
              if(INSTANCE == null) {
                 synchronized(DoubleCheckedLockingSingleton.class) {
                     // Double checking Singleton instance
                     if(INSTANCE == null) {
                         INSTANCE = new DoubleCheckedLockingSingleton();
                     }
                 }
              }
              return INSTANCE;
          }
     }
    
  3. Static factory method

     /**
     * Singleton pattern example with static factory method
     */
    
     public class Singleton {
         // Initialized during class loading
         private static final Singleton INSTANCE = new Singleton();
    
         // To prevent creating another instance of 'Singleton'
         private Singleton() {}
    
         public static Singleton getSingleton() {
             return INSTANCE;
         }
     }
    

How to save a dictionary to a file?

I'm not sure what your first question is, but if you want to save a dictionary to file you should use the json library. Look up the documentation of the loads and puts functions.

Inconsistent Accessibility: Parameter type is less accessible than method

If sounds like the type ACTInterface is not public, but is using the default accessibility of either internal (if it is top-level) or private (if it is nested in another type).

Giving the type the public modifier would fix it.

Another approach is to make both the type and the method internal, if that is your intent.

The issue is not the accessibility of the field (oActInterface), but rather of the type ACTInterface itself.

Python string prints as [u'String']

[u'ABC'] would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.

I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:

 soup[0].encode("ascii")

However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.

 soup[0].encode("latin-1")


 soup[0].encode("utf-8")

Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:

 soup[0].encode(soup.originalEncoding)

How do I create a copy of an object in PHP?

The answers are commonly found in Java books.

  1. cloning: If you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.

  2. serialization/deserialization

$new_object = unserialize(serialize($your_object))

This achieves deep copy with a heavy cost depending on the complexity of the object.

How to format a DateTime in PowerShell

If you got here to use this in cmd.exe (in a batch file):

powershell -Command (Get-Date).ToString('yyyy-MM-dd')

Laravel 5.4 redirection to custom url after login

For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME; with protected $redirectTo = '/newurl'; and replace newurl accordingly.

Tested with Laravel version-6

How to underline a UILabel in swift?

You can do this using NSAttributedString

Example:

let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

EDIT

To have the same attributes for all texts of one UILabel, I suggest you to subclass UILabel and overriding text, like that:

Swift 5

Same as Swift 4.2 but: You should prefer the Swift initializer NSRange over the old NSMakeRange, you can shorten to .underlineStyle and linebreaks improve readibility for long method calls.

class UnderlinedLabel: UILabel {

override var text: String? {
    didSet {
        guard let text = text else { return }
        let textRange = NSRange(location: 0, length: text.count)
        let attributedText = NSMutableAttributedString(string: text)
        attributedText.addAttribute(.underlineStyle,
                                    value: NSUnderlineStyle.single.rawValue,
                                    range: textRange)
        // Add other attributes if needed
        self.attributedText = attributedText
        }
    }
}

Swift 4.2

class UnderlinedLabel: UILabel {

override var text: String? {
    didSet {
        guard let text = text else { return }
        let textRange = NSMakeRange(0, text.count)
        let attributedText = NSMutableAttributedString(string: text)
        attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
        // Add other attributes if needed
        self.attributedText = attributedText
        }
    }
}

Swift 3.0

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            self.attributedText = attributedText
        }
    }
}

And you put your text like this :

@IBOutlet weak var label: UnderlinedLabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.text = "StringWithUnderLine"
    }

OLD:

Swift (2.0 to 2.3):

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

Swift 1.2:

class UnderlinedLabel: UILabel {
    
    override var text: String! {
        didSet {
            let textRange = NSMakeRange(0, count(text))
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

This kind of thing happened to me when I was using php language construct exit; in middle of transaction. Then this transaction "hangs" and you need to kill mysql process (described above with processlist;)

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

The universal adb driver installer worked for me. I went from an HTC to a Samsung to a LG Nexus. The drivers are all over the place for me.

http://adbdriver.com/

What are the main differences between JWT and OAuth authentication?

It looks like everybody who answered here missed the moot point of OAUTH

From Wikipedia

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.

The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access

There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points

You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general

Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials

C/C++ maximum stack size of program

Yes, there is a possibility of stack overflow. The C and C++ standard do not dictate things like stack depth, those are generally an environmental issue.

Most decent development environments and/or operating systems will let you tailor the stack size of a process, either at link or load time.

You should specify which OS and development environment you're using for more targeted assistance.

For example, under Ubuntu Karmic Koala, the default for gcc is 2M reserved and 4K committed but this can be changed when you link the program. Use the --stack option of ld to do that.

How to run Python script on terminal?

You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial: http://docs.python-guide.org/en/latest/starting/install3/osx/.

To run the program you can then copy and paste in this code:

python /Users/luca/Documents/python/gameover.py

Or you can go to the directory of the file with cd followed by the folder. When you are in the folder you can then python YourFile.py.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I've just experienced this issue. For me it appeared when some erroneous code was trying to redirect to HTTPS on port 80.

e.g.

https://example.com:80/some/page

by removing the port 80 from the url, the redirect works.

HTTPS by default runs over port 443.

What is the best way to programmatically detect porn images?

You can find many whitepapers on the net dealing with this subject.

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

Creating a "Hello World" WebSocket example

I couldnt find a simple working example anywhere (as of Jan 19), so here is an updated version. I have chrome version 71.0.3578.98.

C# Websocket server :

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;

namespace WebSocketServer
{
    class Program
    {
    static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    static void Main(string[] args)
    {
        serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
        serverSocket.Listen(1); //just one socket
        serverSocket.BeginAccept(null, 0, OnAccept, null);
        Console.Read();
    }

    private static void OnAccept(IAsyncResult result)
    {
        byte[] buffer = new byte[1024];
        try
        {
            Socket client = null;
            string headerResponse = "";
            if (serverSocket != null && serverSocket.IsBound)
            {
                client = serverSocket.EndAccept(result);
                var i = client.Receive(buffer);
                headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                // write received data to the console
                Console.WriteLine(headerResponse);
                Console.WriteLine("=====================");
            }
            if (client != null)
            {
                /* Handshaking and managing ClientSocket */
                var key = headerResponse.Replace("ey:", "`")
                          .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                          .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                          .Trim();

                // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                var test1 = AcceptKey(ref key);

                var newLine = "\r\n";

                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                     //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                     //+ "Sec-WebSocket-Version: 13" + newLine
                     ;

                client.Send(System.Text.Encoding.UTF8.GetBytes(response));
                var i = client.Receive(buffer); // wait for client to send a message
                string browserSent = GetDecodedData(buffer, i);
                Console.WriteLine("BrowserSent: " + browserSent);

                Console.WriteLine("=====================");
                //now send message to client
                client.Send(GetFrameFromString("This is message from server to client."));
                System.Threading.Thread.Sleep(10000);//wait for message to be sent
            }
        }
        catch (SocketException exception)
        {
            throw exception;
        }
        finally
        {
            if (serverSocket != null && serverSocket.IsBound)
            {
                serverSocket.BeginAccept(null, 0, OnAccept, null);
            }
        }
    }

    public static T[] SubArray<T>(T[] data, int index, int length)
    {
        T[] result = new T[length];
        Array.Copy(data, index, result, 0, length);
        return result;
    }

    private static string AcceptKey(ref string key)
    {
        string longKey = key + guid;
        byte[] hashBytes = ComputeHash(longKey);
        return Convert.ToBase64String(hashBytes);
    }

    static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
    private static byte[] ComputeHash(string str)
    {
        return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
    }

    //Needed to decode frame
    public static string GetDecodedData(byte[] buffer, int length)
    {
        byte b = buffer[1];
        int dataLength = 0;
        int totalLength = 0;
        int keyIndex = 0;

        if (b - 128 <= 125)
        {
            dataLength = b - 128;
            keyIndex = 2;
            totalLength = dataLength + 6;
        }

        if (b - 128 == 126)
        {
            dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
            keyIndex = 4;
            totalLength = dataLength + 8;
        }

        if (b - 128 == 127)
        {
            dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
            keyIndex = 10;
            totalLength = dataLength + 14;
        }

        if (totalLength > length)
            throw new Exception("The buffer length is small than the data length");

        byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };

        int dataIndex = keyIndex + 4;
        int count = 0;
        for (int i = dataIndex; i < totalLength; i++)
        {
            buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
            count++;
        }

        return Encoding.ASCII.GetString(buffer, dataIndex, dataLength);
    }

    //function to create  frames to send to client 
    /// <summary>
    /// Enum for opcode types
    /// </summary>
    public enum EOpcodeType
    {
        /* Denotes a continuation code */
        Fragment = 0,

        /* Denotes a text code */
        Text = 1,

        /* Denotes a binary code */
        Binary = 2,

        /* Denotes a closed connection */
        ClosedConnection = 8,

        /* Denotes a ping*/
        Ping = 9,

        /* Denotes a pong */
        Pong = 10
    }

    /// <summary>Gets an encoded websocket frame to send to a client from a string</summary>
    /// <param name="Message">The message to encode into the frame</param>
    /// <param name="Opcode">The opcode of the frame</param>
    /// <returns>Byte array in form of a websocket frame</returns>
    public static byte[] GetFrameFromString(string Message, EOpcodeType Opcode = EOpcodeType.Text)
    {
        byte[] response;
        byte[] bytesRaw = Encoding.Default.GetBytes(Message);
        byte[] frame = new byte[10];

        int indexStartRawData = -1;
        int length = bytesRaw.Length;

        frame[0] = (byte)(128 + (int)Opcode);
        if (length <= 125)
        {
            frame[1] = (byte)length;
            indexStartRawData = 2;
        }
        else if (length >= 126 && length <= 65535)
        {
            frame[1] = (byte)126;
            frame[2] = (byte)((length >> 8) & 255);
            frame[3] = (byte)(length & 255);
            indexStartRawData = 4;
        }
        else
        {
            frame[1] = (byte)127;
            frame[2] = (byte)((length >> 56) & 255);
            frame[3] = (byte)((length >> 48) & 255);
            frame[4] = (byte)((length >> 40) & 255);
            frame[5] = (byte)((length >> 32) & 255);
            frame[6] = (byte)((length >> 24) & 255);
            frame[7] = (byte)((length >> 16) & 255);
            frame[8] = (byte)((length >> 8) & 255);
            frame[9] = (byte)(length & 255);

            indexStartRawData = 10;
        }

        response = new byte[indexStartRawData + length];

        int i, reponseIdx = 0;

        //Add the frame bytes to the reponse
        for (i = 0; i < indexStartRawData; i++)
        {
            response[reponseIdx] = frame[i];
            reponseIdx++;
        }

        //Add the data bytes to the response
        for (i = 0; i < length; i++)
        {
            response[reponseIdx] = bytesRaw[i];
            reponseIdx++;
        }

        return response;
    }
}
}

Client html and javascript:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"_x000D_
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <script type="text/javascript">_x000D_
        var socket = new WebSocket('ws://localhost:8080/websession');_x000D_
        socket.onopen = function() {_x000D_
           // alert('handshake successfully established. May send data now...');_x000D_
     socket.send("Hi there from browser.");_x000D_
        };_x000D_
  socket.onmessage = function (evt) {_x000D_
                //alert("About to receive data");_x000D_
                var received_msg = evt.data;_x000D_
                alert("Message received = "+received_msg);_x000D_
            };_x000D_
        socket.onclose = function() {_x000D_
            alert('connection closed');_x000D_
        };_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to make a SIMPLE C++ Makefile

I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.

appname := myapp

CXX := g++
CXXFLAGS := -Wall -g

srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects  := $(patsubst %.cpp, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.

Node.js throws "btoa is not defined" error

I have a code shared between server and client and I needed an implementation of btoa inside it. I tried doing something like:

const btoaImplementation =  btoa || (str => Buffer.from(str).toString('base64'));

but the Server would crush with:

ReferenceError: btoa is not defined

while Buffer is not defined on the client.

I couldn't check window.btoa (it's a shared code, remember?)

So I ended up with this implementation:

const btoaImplementation = str => {
    try {
        return btoa(str);
    } catch(err) {
        return Buffer.from(str).toString('base64')
    }
};

Generic List - moving an item within the list

Simplest way:

list[newIndex] = list[oldIndex];
list.RemoveAt(oldIndex);

EDIT

The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

    public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
    {
        T aux = list[newIndex];
        list[newIndex] = list[oldIndex];
        list[oldIndex] = aux;
    }

This solution is the fastest because it doesn't involve list insertions/removals.

Stacking DIVs on top of each other?

You can now use CSS Grid to fix this.

<div class="outer">
  <div class="top"> </div>
  <div class="below"> </div>
</div>

And the css for this:

.outer {
  display: grid;
  grid-template: 1fr / 1fr;
  place-items: center;
}
.outer > * {
  grid-column: 1 / 1;
  grid-row: 1 / 1;
}
.outer .below {
  z-index: 2;
}
.outer .top {
  z-index: 1;
}

Get root view from current activity

This is what I use to get the root view as found in the XML file assigned with setContentView:

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);

how to use sqltransaction in c#

You can create a SqlTransaction from a SqlConnection.

And use it to create any number of SqlCommands

SqlTransaction transaction = connection.BeginTransaction();
var cmd1 = new SqlCommand(command1Text, connection, transaction);
var cmd2 = new SqlCommand(command2Text, connection, transaction);

Or

var cmd1 = new SqlCommand(command1Text, connection, connection.BeginTransaction());
var cmd2 = new SqlCommand(command2Text, connection, cmd1.Transaction);

If the failure of commands never cause unexpected changes don't use transaction.

if the failure of commands might cause unexpected changes put them in a Try/Catch block and rollback the operation in another Try/Catch block.

Why another try/catch? According to MSDN:

Try/Catch exception handling should always be used when rolling back a transaction. A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

Here is a sample code:

string connStr = "[connection string]";
string cmdTxt = "[t-sql command text]";

using (var conn = new SqlConnection(connStr))
{
    conn.Open();
    var cmd = new SqlCommand(cmdTxt, conn, conn.BeginTransaction());


    try
    {
        cmd.ExecuteNonQuery();
        //before this line, nothing has happened yet
        cmd.Transaction.Commit();
    }
    catch(System.Exception ex)
    {
        //You should always use a Try/Catch for transaction's rollback
        try
        {
            cmd.Transaction.Rollback();
        }
        catch(System.Exception ex2)
        {
            throw ex2;
        }
        throw ex;
    }

    conn.Close();
}

The transaction is rolled back in the event it is disposed before Commit or Rollback is called.

So you don't need to worry about app being closed.

How to add a class to body tag?

This should do it:

var newClass = window.location.href;
newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
$('body').addClass(newClass);

The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);

That pattern should yield the following:

  • ../about_us.html : about
  • ../something.html : something
  • ../has_two_underscores.html : has

What is the facade design pattern?

Wikipedia has a great example of Facade pattern.

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

Multi-Line Comments in Ruby?

=begin
(some code here)
=end

and

# This code
# on multiple lines
# is commented out

are both correct. The advantage of the first type of comment is editability—it's easier to uncomment because fewer characters are deleted. The advantage of the second type of comment is readability—reading the code line by line, it's much easier to tell that a particular line has been commented out. Your call but think about who's coming after you and how easy it is for them to read and maintain.

How to drop SQL default constraint without knowing its name?

I found that this works and uses no joins:

DECLARE @ObjectName NVARCHAR(100)
SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID('[tableSchema].[tableName]') AND [name] = 'columnName';
EXEC('ALTER TABLE [tableSchema].[tableName] DROP CONSTRAINT ' + @ObjectName)

Just make sure that columnName does not have brackets around it because the query is looking for an exact match and will return nothing if it is [columnName].

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

PHP $_POST not working?

  1. html file and php file both should reside in htdocs folder in c:\apache2 (if you use apache web server).
  2. Open html file by typing http://"localhost/html_file_name.html"
  3. Now enter Your data in fields.. Your code will run..

What is the difference between Builder Design pattern and Factory Design pattern?

IMHO

Builder is some kind of more complex Factory.

But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.

So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:

Dependency Injection Container -> Service Locator -> Builder -> Factory

C++ Redefinition Header Files (winsock2.h)

I checked the recursive includes, I spotted the header files which include (recursively) some #include "windows.h" and #include "Winsock.h" and write a #include "Winsock2.h". in this files, i added #include "Winsock2.h" as the first include.

Just a matter of patience, look at includes one by one and establish this order, first #include "Winsock2.h" then #include "windows.h"

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

SVN how to resolve new tree conflicts when file is added on two branches

I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.

The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?

Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.

MySQL Removing Some Foreign keys

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region; This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION Now simply issue an:

alter table region drop foreign key region_ibfk_1;

or

more simply just type:- alter table TableName drop foreign key TableName_ibfk_1;

remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1

How to distinguish mouse "click" and "drag"

For a public action on an OSM map (position a marker on click) the question was: 1) how to determine the duration of mouse down->up (you can't imagine creating a new marker for each click) and 2) did the mouse move during down->up (i.e user is dragging the map).

const map = document.getElementById('map');

map.addEventListener("mousedown", position); 
map.addEventListener("mouseup", calculate);

let posX, posY, endX, endY, t1, t2, action;

function position(e) {

  posX = e.clientX;
  posY = e.clientY;
  t1 = Date.now();

}

function calculate(e) {

  endX = e.clientX;
  endY = e.clientY;
  t2 = (Date.now()-t1)/1000;
  action = 'inactive';

  if( t2 > 0.5 && t2 < 1.5) { // Fixing duration of mouse down->up

      if( Math.abs( posX-endX ) < 5 && Math.abs( posY-endY ) < 5 ) { // 5px error on mouse pos while clicking
         action = 'active';
         // --------> Do something
      }
  }
  console.log('Down = '+posX + ', ' + posY+'\nUp = '+endX + ', ' + endY+ '\nAction = '+ action);    

}

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

How to unmount a busy device

Niche Answer:

If you have a zfs pool on that device, at least when it's a file-based pool, lsof will not show the usage. But you can simply run

sudo zpool export mypoo

and then unmount.

Excel: the Incredible Shrinking and Expanding Controls

Although there are clearly numerous reasons for this behavior, several answers point to issues with scaling and screen resolutions. One workaround is to use the following functions to resize and anchor the controls to a specific cell:

Sub ResizeCombo(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long, ByVal wid As Long)        
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 1
    cbo.Width = wid    
End Sub

Sub ResizeCheckbox(ByRef cbo As Shape, ByVal rw As Long, ByVal cl As Long)
    cbo.Height = Intake.Cells(rw, cl).Height - 1
    cbo.Top = Intake.Cells(rw, cl).Top + 1
    cbo.Left = Intake.Cells(rw, cl).Left + 6
    cbo.Width = Intake.Cells(rw, cl).MergeArea.Width - 7        
End Sub

Sub ResizeCombos()
    ResizeCombo Intake.Shapes("School"), 11, 1, 144

    ResizeCheckbox Intake.Shapes("cbReading"), 70, 1

    ''ResizeCombo also works for option buttons
    ResizeCombo Intake.Shapes("obGenderMale"), 20, 8, 45
    ResizeCombo Intake.Shapes("obGenderFemale"), 20, 9,50

HOWEVER, recently this workaround stopped working. I've been banging against it for days until I discovered that the zoom level of the sheet had been adjusted to 105%! Resetting it to 100% resolved the problem. However what if the user needs a higher zoom level? I figured out that I can change the zoom after resizing and things stay where they were meant to. My calling function now looks like this:

Sub refresh()
    OldZoom = ActiveWindow.Zoom
    ActiveWindow.Zoom = 100
    Call ResizeCombos
    ActiveWindow.Zoom = OldZoom
End Sub

So far it is working!

When should I use a List vs a LinkedList

The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc.

The key difference comes when performance matter. For example, if you are implementing the list that has heavy "INSERT" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. http://en.wikipedia.org/wiki/Linked_list and Array

Hope this help,

How to change package name in flutter?

For those like me that doesn't like to change specific files, I've used https://pub.dev/packages/rename.

Using this, you simply run these commands in your terminal and your app name and identifiers will be changed.pub global run

Installing: pub global activate rename

And then, Run this command inside your flutter project root.

pub global run rename --bundleId com.example.android.app --target android

Find size of object instance in bytes in c#

Use Son Of Strike which has a command ObjSize.

Note that actual memory consumed is always larger than ObjSize reports due to a synkblk which resides directly before the object data.

Read more about both here MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects.

How do I display local image in markdown?

In Jupyter Notebook Markdown, you can use

<img src="RelPathofFolder/File" style="width:800px;height:300px;">

XML element with attribute and content using JAXB

Updated Solution - using the schema solution that we were debating. This gets you to your answer:

Sample Schema:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport" 
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" 
jaxb:version="2.0">

<complexType name="sportType">
    <attribute name="type" type="string" />
    <attribute name="gender" type="string" />
</complexType>

<element name="sports">
    <complexType>
        <sequence>
            <element name="sport" minOccurs="0" maxOccurs="unbounded"
                type="tns:sportType" />
        </sequence>
    </complexType>
</element>

Code Generated

SportType:

package org.example.sport; 

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {

    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String gender;

    public String getType() {
        return type;
    }


    public void setType(String value) {
        this.type = value;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String value) {
        this.gender = value;
    }

}

Sports:

package org.example.sport;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
        "sport"
})
@XmlRootElement(name = "sports")
public class Sports {

    protected List<SportType> sport;

    public List<SportType> getSport() {
        if (sport == null) {
            sport = new ArrayList<SportType>();
        }
        return this.sport;
    }

}

Output class files are produced by running xjc against the schema on the command line

How to use pip on windows behind an authenticating proxy

I had the same issue on a remote windows environment. I tried many solutions found here or on other similars posts but nothing worked. Finally, the solution was quite simple. I had to set NO_PROXY with cmd :

set NO_PROXY="<domain>\<username>:<password>@<host>:<port>"
pip install <packagename>

You have to use double quotes and set NO_PROXY to upper case. You can also add NO_PROXY as an environment variable instead of setting it each time you use the console.

I hope this will help if any other solution posted here works.

How to explain callbacks in plain english? How are they different from calling one function from another function?

Always better to start with an example :).

Let's assume you have two modules A and B.

You want module A to be notified when some event/condition occurs in module B. However, module B has no idea about your module A. All it knows is an address to a particular function (of module A) through a function pointer that is provided to it by module A.

So all B has to do now, is "callback" into module A when a particular event/condition occurs by using the function pointer. A can do further processing inside the callback function.

*) A clear advantage here is that you are abstracting out everything about module A from module B. Module B does not have to care who/what module A is.

Deserializing a JSON file with JavaScriptSerializer()

Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:

string s = //{ "user" : {    "id" : 12345,    "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);

You'll get back something, where you can do:

var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.

Look at result in the debugger to see, what's in there.

Should operator<< be implemented as a friend or as a member function?

The problem here is in your interpretation of the article you link.

Equality

This article is about somebody that is having problems correctly defining the bool relationship operators.

The operator:

  • Equality == and !=
  • Relationship < > <= >=

These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).

There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.

Streaming

The stream operators:

  • operator << output
  • operator >> input

When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.

It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.

#include <iostream>

class Paragraph
{
    public:
        explicit Paragraph(std::string const& init)
            :m_para(init)
        {}

        std::string const&  to_str() const
        {
            return m_para;
        }

        bool operator==(Paragraph const& rhs) const
        {
            return m_para == rhs.m_para;
        }
        bool operator!=(Paragraph const& rhs) const
        {
            // Define != operator in terms of the == operator
            return !(this->operator==(rhs));
        }
        bool operator<(Paragraph const& rhs) const
        {
            return  m_para < rhs.m_para;
        }
    private:
        friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
        std::string     m_para;
};

std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
    return os << p.to_str();
}


int main()
{
    Paragraph   p("Plop");
    Paragraph   q(p);

    std::cout << p << std::endl << (p == q) << std::endl;
}

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

I had this same issue and wondered why it didn't happen with a bitbucket repo that was cloned with https. Looking into it a bit I found that the config for the BB repo had a URL that included my username. So I manually edited the config for my GH repo like so and voila, no more username prompt. I'm on Windows.

Edit your_repo_dir/.git/config (remember: .git folder is hidden)

Change:

https://github.com/WEMP/project-slideshow.git

to:

https://*username*@github.com/WEMP/project-slideshow.git

Save the file. Do a git pull to test it.

The proper way to do this is probably by using git bash commands to edit the setting, but editing the file directly didn't seem to be a problem.

Extract value of attribute node via XPath

To get just the value (without attribute names), use string():

string(//Parent[@id='1']/Children/child/@name)

The fn:string() fucntion will return the value of its argument as xs:string. In case its argument is an attribute, it will therefore return the attribute's value as xs:string.

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Java 8 stream reverse order

This method works with any Stream and is Java 8 compliant:

Stream<Integer> myStream = Stream.of(1, 2, 3, 4, 5);
myStream.reduce(Stream.empty(),
        (Stream<Integer> a, Integer b) -> Stream.concat(Stream.of(b), a),
        (a, b) -> Stream.concat(b, a))
        .forEach(System.out::println);

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Solved, just renamed the Global.asax or delete it fixed the problem :/

Other known related bugs I found on the web:

  1. Global.asax.cs: must inherit from HttpApplication -> public class MvcApplication : HttpApplication
  2. Project output must be the bin folder and not Bin/Debug, etc.
  3. Iss application pool is not in the correct .net version.

ping response "Request timed out." vs "Destination Host unreachable"

Request timed out means that the local host did not receive a response from the destination host, but it was able to reach it. Destination host unreachable means that there was no valid route to the requested host.

How do I detect a page refresh using jquery?

There are two events on client side as given below.

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

2. window.onload (calls on Page Load)

On server Side

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

_x000D_
_x000D_
 <script type="text/javascript">_x000D_
    window.onbeforeunload = function (e) {_x000D_
        _x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: { IsRefresh: 'Close' }_x000D_
        });_x000D_
    };_x000D_
_x000D_
    window.onload = function (e) {_x000D_
_x000D_
        $.ajax({_x000D_
            type: 'GET',_x000D_
            async: false,_x000D_
            url: '/Home/TestAjax',_x000D_
            data: {IsRefresh:'Load'}_x000D_
        });_x000D_
    };_x000D_
</script>
_x000D_
_x000D_
_x000D_

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

Get href attribute on jQuery

Use this:

$(function(){
    $("tr.b_row").each(function(){
    var a_href = $(this).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);

    });
});

See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/

dataframe: how to groupBy/count then filter on count in Scala

When you pass a string to the filter function, the string is interpreted as SQL. Count is a SQL keyword and using count as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).

You can easily avoid this by using a column expression instead of a String:

df.groupBy("x").count()
  .filter($"count" >= 2)
  .show()

How to escape the % (percent) sign in C's printf?

You can escape it by posting a double '%' like this: %%

Using your example:

printf("hello%%");

Escaping '%' sign is only for printf. If you do:

char a[5];
strcpy(a, "%%");
printf("This is a's value: %s\n", a);

It will print: This is a's value: %%

How to Check byte array empty or not?

In Android Studio version 3.4.1

if(Attachment != null)
{
   code here ...
}

Hashcode and Equals for Hashset

according jdk source code from javasourcecode.org, HashSet use HashMap as its inside implementation, the code about put method of HashSet is below :

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

The rule is firstly check the hash, then check the reference and then call equals method of the object will be putted in.

Add context path to Spring Boot application

For below Spring boot 2 version you need to use below code

server:
   context-path: abc    

And For Spring boot 2+ version use below code

server:
  servlet:
    context-path: abc

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

for root, dirs, files in os.walk(directory):
    for file in files:
        floc = file
        im = Image.open(str(directory) + '\\' + floc)
        pix = np.array(im.getdata())
        pixels.append(pix)
        labels.append(1)   # append(i)???

So far ok. But you want to leave pixels as a list until you are done with the iteration.

pixels = np.array(pixels)
labels = np.array(labels)

You had this indention right in your other question. What happened? previous

Iterating, collecting values in a list, and then at the end joining things into a bigger array is the right way. To make things clear I often prefer to use notation like:

alist = []
for ..
    alist.append(...)
arr = np.array(alist)

If names indicate something about the nature of the object I'm less likely to get errors like yours.

I don't understand what you are trying to do with traindata. I doubt if you need to build it during the loop. pixels and labels have the basic information.

That

traindata = np.array([traindata[i][i],traindata[1]], dtype=object)

comes from the previous question. I'm not sure you understand that answer.

traindata = []
traindata.append(pixels)
traindata.append(labels)

if done outside the loop is just

traindata = [pixels, labels]

labels is a 1d array, a bunch of 1s (or [0,1,2,3...] if my guess is right). pixels is a higher dimension array. What is its shape?

Stop right there. There's no point in turning that list into an array. You can save the list with pickle.

You are copying code from an earlier question, and getting the formatting wrong. cPickle very large amount of data

C# DLL config file

For a dll, it should not depend on configuration as configuration is owned by application and not by dll.

This is explained at here

Changing cursor to waiting in javascript/jquery

Override all single element

$("*").css("cursor", "progress");

The condition has length > 1 and only the first element will be used

You get the error because if can only evaluate a logical vector of length 1.

Maybe you miss the difference between & (|) and && (||). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE

You don't need the if statement at all:

mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"

How to update ruby on linux (ubuntu)?

The author of this article claims that it would be best to avoid installing Ruby from the local packet manager, but to use RVM instead.

You can easily switch between different Ruby versions:

rvm use 1.9.3

etc.

How to obtain the last path segment of a URI

Here's a short method to do it:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

Test Code:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}

Output:

42
foo
bar

Explanation:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


$1       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above

Change drive in git bash for windows

Just consider your drive as a folder so do cd e:

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

How to access a preexisting collection with Mongoose?

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {
       collection.find(query).toArray(cb);
   });
}

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

find('foo', {a : 1}, function (err, docs) {
            console.dir(docs);
        });
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Batch file to run a command in cmd within a directory

Chain arbitrary commands using & like this:

command1 & command2 & command3 & ...

Thus, in your particular case, put this line in a batch file on your desktop:

START cmd.exe /k "cd C:\activiti-5.9\setup & ant demo.start"

You can also use && to chain commands, albeit this will perform error checking and the execution chain will break if one of the commands fails. The behaviour is detailed here.

Edit: Intrigued by @James K's comment "You CAN chain the commands, but they will have no effect", I tested some more and to my surprise discovered, that the program I was starting in my original test - firefox.exe - while not existing in a directory in the PATH environment variable, is actually executable anywhere on my system (which really made me wonder - see bottom of answer for explanation). So in fact executing...

START cmd.exe /k "cd C:\progra~1\mozill~1 && firefox"

...didn't prove the solution was working. So I chose another program (nLite) after making sure that it was not executable anywhere on my system:

START cmd.exe /k "cd C:\progra~1\nlite && nlite"

And that works just as my original answer already suggested. A Windows version is not given in the question, but I'm using Windows XP, btw.


If anybody is interested why firefox.exe, while not being in PATH, is executable anywhere on my system - and very probably on yours as well - this is due to a registry key where applications can be registered to be available everywhere. See this SU answer for details.

How to convert milliseconds into human readable form?

Both solutions below use javascript (I had no idea the solution was language agnostic!). Both solutions will need to be extended if capturing durations > 1 month.

Solution 1: Use the Date object

var date = new Date(536643021);
var str = '';
str += date.getUTCDate()-1 + " days, ";
str += date.getUTCHours() + " hours, ";
str += date.getUTCMinutes() + " minutes, ";
str += date.getUTCSeconds() + " seconds, ";
str += date.getUTCMilliseconds() + " millis";
console.log(str);

Gives:

"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"

Libraries are helpful, but why use a library when you can re-invent the wheel! :)

Solution 2: Write your own parser

var getDuration = function(millis){
    var dur = {};
    var units = [
        {label:"millis",    mod:1000},
        {label:"seconds",   mod:60},
        {label:"minutes",   mod:60},
        {label:"hours",     mod:24},
        {label:"days",      mod:31}
    ];
    // calculate the individual unit values...
    units.forEach(function(u){
        millis = (millis - (dur[u.label] = (millis % u.mod))) / u.mod;
    });
    // convert object to a string representation...
    var nonZero = function(u){ return dur[u.label]; };
    dur.toString = function(){
        return units
            .reverse()
            .filter(nonZero)
            .map(function(u){
                return dur[u.label] + " " + (dur[u.label]==1?u.label.slice(0,-1):u.label);
            })
            .join(', ');
    };
    return dur;
};

Creates a "duration" object, with whatever fields you require. Formatting a timestamp then becomes simple...

console.log(getDuration(536643021).toString());

Gives:

"6 days, 5 hours, 4 minutes, 3 seconds, 21 millis"

Creating a directory in /sdcard fails

The correct path to the sdcard is

/mnt/sdcard/

but, as answered before, you shouldn't hardcode it. If you are on Android 2.1 or after, use

getExternalFilesDir(String type) 

Otherwise:

Environment.getExternalStorageDirectory()

Read carefully https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Also, you'll need to use this method or something similar

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

then check if you can access the sdcard. As said, read the official documentation.

Another option, maybe you need to use mkdirs instead of mkdir

file.mkdirs()

Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.

What command shows all of the topics and offsets of partitions in Kafka?

Kafka ships with some tools you can use to accomplish this.

List topics:

# ./bin/kafka-topics.sh --list --zookeeper localhost:2181
test_topic_1
test_topic_2
...

List partitions and offsets:

# ./bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --broker-info --group test_group --topic test_topic --zookeeper localhost:2181
Group           Topic                  Pid Offset          logSize         Lag             Owner
test_group      test_topic             0   698020          698021          1              test_group-0
test_group      test_topic             1   235699          235699          0               test_group-1
test_group      test_topic             2   117189          117189          0               test_group-2

Update for 0.9 (and higher) consumer APIs

If you're using the new apis, there's a new tool you can use: kafka-consumer-groups.sh.

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group count_errors --describe
GROUP                          TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             OWNER
count_errors                   logs                           2          2908278         2908278         0               consumer-1_/10.8.0.55
count_errors                   logs                           3          2907501         2907501         0               consumer-1_/10.8.0.43
count_errors                   logs                           4          2907541         2907541         0               consumer-1_/10.8.0.177
count_errors                   logs                           1          2907499         2907499         0               consumer-1_/10.8.0.115
count_errors                   logs                           0          2907469         2907469         0               consumer-1_/10.8.0.126

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

i had the same problem and just easy solve it make sure the package name for package in mainfest tag inside manifest.xml file and the applicationId in application tag inside gradle app level file has the same package name

in manifest.xml

package="com.example.work"

in gradle app level

applicationId "com.example.work"

hope it help

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

Multiple inputs with same name through POST in php

In your html you can pass in an array for the name i.e

<input type="text" name="address[]" /> 

This way php will receive an array of addresses.

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

You can install from nuget as the the below image:

enter image description here

Or, run the below command line on Package Manager Console:

Install-Package Microsoft.AspNet.WebApi

How to determine the Boost version on a system?

Might be already answered, but you can try this simple program to determine if and what installation of boost you have :

#include<boost/version.hpp>
#include<iostream>
using namespace std;
int main()
{
cout<<BOOST_VERSION<<endl;
return 0;
}

How do I convert from BLOB to TEXT in MySQL?

I have had the same problem, and here is my solution:

  1. create new columns of type text in the table for each blob column
  2. convert all the blobs to text and save them in the new columns
  3. remove the blob columns
  4. rename the new columns to the names of the removed ones
ALTER TABLE mytable
ADD COLUMN field1_new TEXT NOT NULL,
ADD COLUMN field2_new TEXT NOT NULL;

update mytable set
field1_new = CONVERT(field1 USING utf8),
field2_new = CONVERT(field2 USING utf8);

alter table mytable
drop column field1,
drop column field2;

alter table mytable
change column field1_new field1 text,
change column field2_new field2 text;

array of string with unknown size

Can you use a List strings and then when you are done use strings.ToArray() to get the array of strings to work with?

How to align text below an image in CSS?

Best way is to wrap the Image and Paragraph text with a DIV and assign a class.

Example:

<div class="image1">
    <div class="imgWrapper">
        <img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
        <p>It's my first Image</p>
    </div>
    ...
    ...
    ...
    ...
</div>

Getting Chrome to accept self-signed localhost certificate

Click anywhere on the page and type a BYPASS_SEQUENCE

"thisisunsafe" is a BYPASS_SEQUENCE for Chrome version 65

"badidea" Chrome version 62 - 64.

"danger" used to work in earlier versions of Chrome

You don't need to look for input field, just type it. It feels strange but it is working.

I tried it on Mac High Sierra.

To double check if they changed it again go to Latest chromium Source Code

To look for BYPASS_SEQUENCE, at the moment it looks like that:

var BYPASS_SEQUENCE = window.atob('dGhpc2lzdW5zYWZl');

Now they have it camouflaged, but to see the real BYPASS_SEQUENCE you can run following line in a browser console.

console.log(window.atob('dGhpc2lzdW5zYWZl'));

How to send a simple string between two programs using pipes?

What one program writes to stdout can be read by another via stdin. So simply, using c, write prog1 to print something using printf() and prog2 to read something using scanf(). Then just run

./prog1 | ./prog2

Path to Powershell.exe (v 2.0)

Here is one way...

(Get-Process powershell | select -First 1).Path

Here is possibly a better way, as it returns the first hit on the path, just like if you had ran Powershell from a command prompt...

(Get-Command powershell.exe).Definition

Common HTTPclient and proxy

Starting from Apache HTTPComponents 4.3.x HttpClientBuilder class sets the proxy defaults from System properties http.proxyHost and http.proxyPort or else you can override them using setProxy method.

how to initialize a char array?

You can use a for loop. but don't forget the last char must be a null character !

char * msg = new char[65546];
for(int i=0;i<65545;i++)
{
    msg[i]='0';
}
msg[65545]='\0';

How to check internet access on Android? InetAddress never times out

It's works for me. Try it out.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        URL url = new URL("http://stackoverflow.com/posts/11642475/edit" );
        //URL url = new URL("http://www.nofoundwebsite.com/" );
        executeReq(url);
        Toast.makeText(getApplicationContext(), "Webpage is available!", Toast.LENGTH_SHORT).show();
    }
    catch(Exception e) {
        Toast.makeText(getApplicationContext(), "oops! webpage is not available!", Toast.LENGTH_SHORT).show();
    }
}

private void executeReq(URL urlObject) throws IOException
{
    HttpURLConnection conn = null;
    conn = (HttpURLConnection) urlObject.openConnection();
    conn.setReadTimeout(30000);//milliseconds
    conn.setConnectTimeout(3500);//milliseconds
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    // Start connect
    conn.connect();
    InputStream response =conn.getInputStream();
    Log.d("Response:", response.toString());
}}

Get selected row item in DataGrid WPF

Just discovered this one after i tried Fara's answer but it didn't work on my project. Just drag the column from the Data Sources window, and drop to the Label or TextBox.

How to do logging in React Native?

Development Time Logging

For development time logging, you can use console.log(). One important thing, if you want to disable logging in production mode, then in Root Js file of app, just assign blank function like this - console.log = {} It will disable whole log publishing throughout app altogether, which actually required in production mode as console.log consumes time.


Run Time Logging

In production mode, it is also required to see logs when real users are using your app in real time. This helps in understanding bugs, usage and unwanted cases. There are many 3rd party paid tools available in the market for this. One of them which I've used is by Logentries

The good thing is that Logentries has got React Native Module as well. So, it will take very less time for you to enable Run time logging with your mobile app.

Should URL be case sensitive?

I am not a fan of bumping old articles but because this was one of the first responses for this particular issue I felt a need to clarify something.

As @Bhavin Shah answer states the domain part of the url is case insensitive, so

http://google.com 

and

http://GOOGLE.COM 

and

http://GoOgLe.CoM 

are all the same but everything after the domain name part is considered case sensitive.

so...

http://GOOGLE.COM/ABOUT

and

http://GOOGLE.COM/about

are different.

Note: I am talking "technically" and not "literally" in a lot of cases, most actually, servers are setup to handle these items the same, but it is possible to set them up so they are NOT handled the same.

Different servers handle this differently and in some cases they Have to be case sensitive. In many cases query string values are encoded (such as Session Ids or Base64 encoded data thats passed as a query string value) These items are case sensitive by their nature so the server has to be case sensitive in handling them.

So to answer the question, "should" servers be case sensitive in grabbing this data, the answer is "yes, most definitely."

Of course not everything needs to be case sensitive but the server should be aware of what that is and how to handle those cases.


@Hart Simha's comment basically says the same thing. I missed it before I posted so I want to give credit where credit is due.

Get underlined text with Markdown

Markdown doesn't have a defined syntax to underline text.

I guess this is because underlined text is hard to read, and that it's usually used for hyperlinks.

Adb Devices can't find my phone

I have a ZTE Crescent phone (Orange San Francisco II).

When I connect the phone to the USB a disk shows up in OS X named 'ZTE_USB_Driver'.

Running adb devices displays no connected devices. But after I eject the 'ZTE_USB_Driver' disk from OS X, and run adb devices again the phone shows up as connected.

Take the content of a list and append it to another list

You can simply concatnate two lists, e.g:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

rand() returns the same number each time the program is run

You are not seeding the number.

Use This:

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0)));
    cout << (rand() % 100) << endl;
    return 0;
}

You only need to seed it once though. Basically don't seed it every random number.

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

Aggregate function in SQL WHERE-Clause

You haven't mentioned the DBMS. Assuming you are using MS SQL-Server, I've found a T-SQL Error message that is self-explanatory:

"An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference"

http://www.sql-server-performance.com/


And an example that it is possible in a subquery.

Show all customers and smallest order for those who have 5 or more orders (and NULL for others):

SELECT a.lastname
     , a.firstname
     , ( SELECT MIN( o.amount )
         FROM orders o
         WHERE a.customerid = o.customerid
           AND COUNT( a.customerid ) >= 5
        )
        AS smallestOrderAmount
FROM account a
GROUP BY a.customerid
       , a.lastname
       , a.firstname ;

UPDATE.

The above runs in both SQL-Server and MySQL but it doesn't return the result I expected. The next one is more close. I guess it has to do with that the field customerid, GROUPed BY and used in the query-subquery join is in the first case PRIMARY KEY of the outer table and in the second case it's not.

Show all customer ids and number of orders for those who have 5 or more orders (and NULL for others):

SELECT o.customerid
     , ( SELECT COUNT( o.customerid )
         FROM account a
         WHERE a.customerid = o.customerid
           AND COUNT( o.customerid ) >= 5
        )
        AS cnt
FROM orders o
GROUP BY o.customerid ;

Remove special symbols and extra spaces and replace with underscore using the replace method

If you have a text as

var sampleText ="ä_öü_ßÄ_ TESTED Ö_Ü!@#$%^&())(&&++===.XYZ"

To replace all special character (!@#$%^&())(&&++= ==.) without replacing the characters(including umlaut)

Use below regex

sampleText = sampleText.replace(/[`~!@#$%^&*()|+-=?;:'",.<>{}[]\/\s]/gi,'');

OUTPUT : sampleText = "ä_öü_ßÄ____TESTED_Ö_Ü_____________________XYZ"

This would replace all with an underscore which is provided as second argument to the replace function.You can add whatever you want as per your requirement

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

Experimenting more, the underlying cause in my app (calling goog.userAgent.adobeReader) was accessing Adobe Reader via an ActiveXObject on the page with the link to the PDF. This minimal test case causes the gray screen for me (however removing the ActiveXObject causes no gray screen).

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>hi</title>
    <meta charset="utf-8">
  </head>
  <body>
    <script>
      new ActiveXObject('AcroPDF.PDF.1');
    </script>
    <a target="_blank" href="http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf">link</a>
  </body>
</html>

I'm very interested if others are able to reproduce the problem with this test case and following the steps from my other post ("I don't have an exact solution...") on a "slow" computer.

Sorry for posting a new answer, but I couldn't figure out how to add a code block in a comment on my previous post.

For a video example of this minimal test case, see: http://youtu.be/IgEcxzM6Kck

How to apply shell command to each line of a command output?

You can use a for loop:

for file in * ; do
   echo "$file"
done

Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.

How to generate XML from an Excel VBA macro?

Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)

Script:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub

What is the best way to uninstall gems from a rails3 project?

This will uninstall a gem installed by bundler:

bundle exec gem uninstall GEM_NAME

Note that this throws

ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>

but the gem is actually removed. Next time you run bundle install the gem will be reinstalled.

Search for a string in all tables, rows and columns of a DB

@NLwino, yery good query with a few errors for keyword usage. I had to modify it a little to wrap the keywords with [ ] and also look char and ntext columns.

    DECLARE @searchstring  NVARCHAR(255)
    SET @searchstring = '%WDB1014%'

    DECLARE @sql NVARCHAR(max)

    SELECT @sql = STUFF((
      SELECT ' UNION ALL SELECT ''' + TABLE_NAME + ''' AS tbl, ''' + COLUMN_NAME + ''' AS col, [' + COLUMN_NAME + '] AS val' + 
        ' FROM ' + TABLE_SCHEMA + '.[' + TABLE_NAME + 
        '] WHERE [' + COLUMN_NAME + '] LIKE ''' + @searchstring + ''''
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE DATA_TYPE in ('nvarchar', 'varchar', 'char', 'ntext')
                  FOR XML PATH('')
             ) ,1, 11, '')

    Exec (@sql)

I ran it on 2.5 GB database and it came back in 51 seconds

How to change the background color of Action Bar's Option Menu in Android 4.2?

I used this and it works just fine.

Apply this code in the onCreate() function

val actionBar: android.support.v7.app.ActionBar? = supportActionBar
    actionBar?.setBackgroundDrawable(ColorDrawable(Color.parseColor("Your color code here")))    

Unresolved external symbol on static class members

Static data members declarations in the class declaration are not definition of them. To define them you should do this in the .CPP file to avoid duplicated symbols.

The only data you can declare and define is integral static constants. (Values of enums can be used as constant values as well)

You might want to rewrite your code as:

class test {
public:
  const static unsigned char X = 1;
  const static unsigned char Y = 2;
  ...
  test();
};

test::test() {
}

If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:

.H :

class test {
public:

  static unsigned char X;
  static unsigned char Y;

  ...

  test();
};

.CPP :

unsigned char test::X = 1;
unsigned char test::Y = 2;

test::test()
{
  // constructor is empty.
  // We don't initialize static data member here, 
  // because static data initialization will happen on every constructor call.
}

app-release-unsigned.apk is not signed

If anyone wants to debug and release separate build variant using Android Studio 3.5, follow the below steps: 1. Set build variant to release mode.

Build Variant

  1. Go to File >> Project Structure
  2. Select Modules, then Signing Config
  3. Click in the Plus icon under Signing Config

Signing Config

  1. Select release section and Provide your release App Information then Apply and OK.

signin

  1. Go to your app level build.gradle and change your buildTypes > "release" section like below Screenshot.

final

Then Run your Project. Happy Coding.

How can I add a custom HTTP header to ajax request with js or jQuery?

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

What is the (best) way to manage permissions for Docker shared volumes?

Base Image

Use this image: https://hub.docker.com/r/reduardo7/docker-host-user

or

Important: this destroys container portability across hosts.

1) init.sh

#!/bin/bash

if ! getent passwd $DOCKDEV_USER_NAME > /dev/null
  then
    echo "Creating user $DOCKDEV_USER_NAME:$DOCKDEV_GROUP_NAME"
    groupadd --gid $DOCKDEV_GROUP_ID -r $DOCKDEV_GROUP_NAME
    useradd --system --uid=$DOCKDEV_USER_ID --gid=$DOCKDEV_GROUP_ID \
        --home-dir /home --password $DOCKDEV_USER_NAME $DOCKDEV_USER_NAME
    usermod -a -G sudo $DOCKDEV_USER_NAME
    chown -R $DOCKDEV_USER_NAME:$DOCKDEV_GROUP_NAME /home
  fi

sudo -u $DOCKDEV_USER_NAME bash

2) Dockerfile

FROM ubuntu:latest
# Volumes
    VOLUME ["/home/data"]
# Copy Files
    COPY /home/data/init.sh /home
# Init
    RUN chmod a+x /home/init.sh

3) run.sh

#!/bin/bash

DOCKDEV_VARIABLES=(\
  DOCKDEV_USER_NAME=$USERNAME\
  DOCKDEV_USER_ID=$UID\
  DOCKDEV_GROUP_NAME=$(id -g -n $USERNAME)\
  DOCKDEV_GROUP_ID=$(id -g $USERNAME)\
)

cmd="docker run"

if [ ! -z "${DOCKDEV_VARIABLES}" ]; then
  for v in ${DOCKDEV_VARIABLES[@]}; do
    cmd="${cmd} -e ${v}"
  done
fi

# /home/usr/data contains init.sh
$cmd -v /home/usr/data:/home/data -i -t my-image /home/init.sh

4) Build with docker

4) Run!

sh run.sh

How to make padding:auto work in CSS?

if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:

* {
  padding: initial;
}

if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.

Pass array to where in Codeigniter Active Record

$this->db->where_in('id', ['20','15','22','42','86']);

Reference: where_in

How to check SQL Server version

Simply use

SELECT @@VERSION

Sample output

Microsoft SQL Server 2012 - 11.0.2100.60 (X64) 
Feb 10 2012 19:39:15 
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )

Source: How to check sql server version? (Various ways explained)

How to check cordova android version of a cordova/phonegap project?

Try

cordova platform version

It will give you the following output

Installed platforms: android 3.5.1, ios 3.5.0
Available platforms: amazon-fireos, blackberry10, browser, firefoxos

Also to know the version of cordodva cli try

cordova -v 

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Use Awk to extract substring

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

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

Same thing but using cut:

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

Or with sed:

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

Even grep:

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

How to create an Oracle sequence starting with max value from a table?

You can't use a subselect inside a CREATE SEQUENCE statement. You'll have to select the value beforehand.

Where does Vagrant download its .box files to?

As mentioned in the docs, boxes are stored at:

  • Mac OS X and Linux: ~/.vagrant.d/boxes
  • Windows: C:/Users/USERNAME/.vagrant.d/boxes

Declaring a python function with an array parameters and passing an array argument to the function call?

I guess I'm unclear about what the OP was really asking for... Do you want to pass the whole array/list and operate on it inside the function? Or do you want the same thing done on every value/item in the array/list. If the latter is what you wish I have found a method which works well.

I'm more familiar with programming languages such as Fortran and C, in which you can define elemental functions which operate on each element inside an array. I finally tracked down the python equivalent to this and thought I would repost the solution here. The key is to 'vectorize' the function. Here is an example:

def myfunc(a,b):
    if (a>b): return a
    else: return b
vecfunc = np.vectorize(myfunc)
result=vecfunc([[1,2,3],[5,6,9]],[7,4,5])
print(result)

Output:

[[7 4 5]
 [7 6 9]]

Ignore <br> with CSS?

As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute.

Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0)

br {
   content: " ";  
   float:right; 
}

I hope this will answer your question!!

Sorting by date & time in descending order?

If you mean you want to sort by date first then by names

SELECT id, name, form_id, DATE(updated_at) as date
  FROM wp_frm_items
  WHERE user_id = 11 && form_id=9
  ORDER BY updated_at DESC,name ASC

This will sort the records by date first, then by names