Programs & Examples On #Bytearrayinputstream

ByteArrayInputStream is a Java and Android class implementing a stream that reads data from a byte array.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

How to convert Java String into byte[]?

The object your method decompressGZIP() needs is a byte[].

So the basic, technical answer to the question you have asked is:

byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only

However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13, the [B means byte[] and 38ee9f13 is the memory address, separated by an @.

For display purposes you can use:

Arrays.toString(bytes);

But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

To get a readable String back from a byte[], use:

String string = new String(byte[] bytes, Charset charset);

The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String, depending upon the chosen charset.

compression and decompression of string data in java

You can't convert binary data to String. As a solution you can encode binary data and then convert to String. For example, look at this How do you convert binary data to Strings and back in Java?

Initial bytes incorrect after Java AES/CBC decryption

This is an improvement over the accepted answer.

Changes:

(1) Using random IV and prepend it to the encrypted text

(2) Using SHA-256 to generate a key from a passphrase

(3) No dependency on Apache Commons

public static void main(String[] args) throws GeneralSecurityException {
    String plaintext = "Hello world";
    String passphrase = "My passphrase";
    String encrypted = encrypt(passphrase, plaintext);
    String decrypted = decrypt(passphrase, encrypted);
    System.out.println(encrypted);
    System.out.println(decrypted);
}

private static SecretKeySpec getKeySpec(String passphrase) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    return new SecretKeySpec(digest.digest(passphrase.getBytes(UTF_8)), "AES");
}

private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
    return Cipher.getInstance("AES/CBC/PKCS5PADDING");
}

public static String encrypt(String passphrase, String value) throws GeneralSecurityException {
    byte[] initVector = new byte[16];
    SecureRandom.getInstanceStrong().nextBytes(initVector);
    Cipher cipher = getCipher();
    cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return DatatypeConverter.printBase64Binary(initVector) +
            DatatypeConverter.printBase64Binary(encrypted);
}

public static String decrypt(String passphrase, String encrypted) throws GeneralSecurityException {
    byte[] initVector = DatatypeConverter.parseBase64Binary(encrypted.substring(0, 24));
    Cipher cipher = getCipher();
    cipher.init(Cipher.DECRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted.substring(24)));
    return new String(original);
}

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I had this problem, but the file was in UTF-8, it was just that somehow on character had come in that was not encoded in UTF-8. To solve the problem I did what is stated in this thread, i.e. I validated the file: How to check whether a file is valid UTF-8?

Basically you run the command:

$ iconv -f UTF-8 your_file -o /dev/null

And if there is something that is not encoded in UTF-8 it will give you the line and row numbers so that you can find it.

how to store Image as blob in Sqlite & how to retrieve it?

In insert()

public void insert(String tableImg, Object object,
        ContentValues dataToInsert) {

   db.insert(tablename, null, dataToInsert);
}

Hope it helps you.

proper hibernate annotation for byte[]

I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:

@Entity
public class ConfigAttribute {
  @Lob
  public byte[] getValueBuffer() {
    return m_valueBuffer;
  }
}

as Oracle has no trouble with that, and for Postgres I'm using custom dialect:

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {

    @Override
    public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
      return BinaryTypeDescriptor.INSTANCE;
    }
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
  }
}

the advantage of this solution I consider, that I can keep hibernate jars untouched.

For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

PowerShell says "execution of scripts is disabled on this system."

you may try this and select "All" Option

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

How do I concatenate two strings in Java?

In java concatenate symbol is "+". If you are trying to concatenate two or three strings while using jdbc then use this:

String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);

Here "" is used for space only.

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

Sockets: Discover port availability using Java

I have Tried something Like this and it worked really fine with me

            Socket Skt;
            String host = "localhost";
            int i = 8983; // port no.

                 try {
                    System.out.println("Looking for "+ i);
                    Skt = new Socket(host, i);
                    System.out.println("There is a Server on port "
                    + i + " of " + host);
                 }
                 catch (UnknownHostException e) {
                    System.out.println("Exception occured"+ e);

                 }
                 catch (IOException e) {
                     System.out.println("port is not used");

                 }

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

Eclipse hangs on loading workbench

I solved deleting *.snap from the workspace dir (and all subdirectories):

metadata\.plugins\*.snap

Checking for a null int value from a Java ResultSet

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

e.g for an Oracle database, use NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

When are static variables initialized?

Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.

How do I delete all the duplicate records in a MySQL table without temp tables

This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:

SELECT DISTINCT * INTO TableA_Verify FROM TableA;

DROP TABLE TableA;

RENAME TABLE TableA_Verify TO TableA;

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

Resize an Array while keeping current elements in Java?

Standard class java.util.ArrayList is resizable array, growing when new elements added.

Oracle listener not running and won't start

In my case, I tried to start the listener via console:

> lsnrctl star

This command printed the following error:

TNS-12560: TNS:protocol adapter error
TNS-00583: Valid node checking: unable to parse configuration parameters

So, I performed the following actions:

  1. Check if Oracle listener.ora or sqlnet.ora file contains special characters
  2. Check if Oracle listener.ora or sqlnet.ora` file are in wrong format or syntax
  3. Check if Oracle listener.ora or sqlnet.ora file have some left justified parenthesis which are not accepted by oracle parser.

Have a look at these files and check the proper syntax. If possible remove/rename sqlnet.ora and try to restart the listener. Or remove/rename both listener.ora or sqlnet.ora file and recreate it properly. These will defenitely resolve the issue.

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

Sniff HTTP packets for GET and POST requests from an application

You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.

Is recursion ever faster than looping?

In general, no, recursion will not be faster than a loop in any realistic usage that has viable implementations in both forms. I mean, sure, you could code up loops that take forever, but there would be better ways to implement the same loop that could outperform any implementation of the same problem via recursion.

You hit the nail on the head regarding the reason; creating and destroying stack frames is more expensive than a simple jump.

However, do note that I said "has viable implementations in both forms". For things like many sorting algorithms, there tends to not be a very viable way of implementing them that doesn't effectively set up its own version of a stack, due to the spawning of child "tasks" that are inherently part of the process. Thus, recursion may be just as fast as attempting to implement the algorithm via looping.

Edit: This answer is assuming non-functional languages, where most basic data types are mutable. It does not apply to functional languages.

How to include a sub-view in Blade templates?

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
  <html stuff>
  @yield('content')
</html>

file: hello.blade.php

@extends('layout')

@section('content')
  <html stuff>
@stop

print variable and a string in python

All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.

variable = 1

print("length " + format(variable))

How do I use the new computeIfAbsent function?

Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:

  // Stores regional movie ratings
  Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();

  // This will throw NullPointerException!
  regionalMovieRatings.get("New York").get(5).add("Boyhood");

  // This will work
  regionalMovieRatings
    .computeIfAbsent("New York", region -> new TreeMap<>())
    .computeIfAbsent(5, rating -> new TreeSet<>())
    .add("Boyhood");

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units

SyntaxError: "can't assign to function call"

You are assigning to a function call:

invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount

which is illegal in Python. The question is, what do you want to do? What does invest() do? I suppose it returns a value, namely what you're trying to use as subsequent_amount, right?

If so, then something like this should work:

amount = invest(amount,top_company(5,year,year+1),year)

Send POST data on redirect with JavaScript/jQuery?

The answers here can be confusing so i will give you a sample code that i am working with.

To start with note that there is no POST parameter to java script windows.location function that you are referring to.

So you have to...

  1. Dynamically make a form with a POST parameter.

  2. Dynamically put a textbox or textboxes with your desired values to post

  3. Invoke the submit form you dynamically created.

And for the example.

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.

On test2.php you can get your values thus.

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

How to select date without time in SQL

select DATE(field) from table;

field value: 2020-12-15 12:19:00

select value: 2020-12-15

How to get row data by clicking a button in a row in an ASP.NET gridview

            <asp:Button  ID="btnEdit" Text="Edit" runat="server"  OnClick="btnEdit_Click" CssClass="CoolButtons"/>


protected void btnEdit_Click(object sender, EventArgs e)
{
       Button btnEdit = (Button)sender;
       GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
      TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
      HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
      TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
     //Get the gridview Row Details
}

And Same As for Delete button

Django MEDIA_URL and MEDIA_ROOT

Following the steps mentioned above for =>3.0 for Debug mode

urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.

Lastly make sure you set the following:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

How to get textLabel of selected row in swift?

Try this:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example

    let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell

    print(currentCell.textLabel!.text)

What's the purpose of SQL keyword "AS"?

When you aren't sure which syntax to choose, especially when there doesn't seem to be much to separate the choices, consult a book on heuristics. As far as I know, the only heuristics book for SQL is 'Joe Celko's SQL Programming Style':

A correlation name is more often called an alias, but I will be formal. In SQL-92, they can have an optional AS operator, and it should be used to make it clear that something is being given a new name. [p16]

This way, if your team doesn't like the convention, you can blame Celko -- I know I do ;)


UPDATE 1: IIRC for a long time, Oracle did not support the AS (preceding correlation name) keyword, which may explain why some old timers don't use it habitually.


UPDATE 2: the term 'correlation name', although used by the SQL Standard, is inappropriate. The underlying concept is that of a ‘range variable’.


UPDATE 3: I just re-read what Celko wrote and he is wrong: the table is not being renamed! I now think:

A correlation name is more often called an alias, but I will be formal. In Standard SQL they can have an optional AS keyword but it should not be used because it may give the impression that something is being renamed when it is not. In fact, it should be omitted to enforce the point that it is a range variable.

Git keeps prompting me for a password

If you want to stop Git from always asking you for the login credentials of your GitHub repository this can be easily done.

Using SSH instead of HTTPS

You can update the origin remote using SSH instead of HTTPS"

git remote set-url origin [email protected]:username/your-repo.git

Configure Git to Store your Password and Username

Here’s how you can make Git store the username and password:

git config --global credential.helper store

Next, save the username and password for a session:

git config --global credential.helper cache

How to pass json POST data to Web API method as an object?

@model MVCClient.Models.ProductDetails

@{
    ViewBag.Title = "ProductDetails";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("#Save").click(function () {
            var ProductDetails = new Object();
            ProductDetails.ProductName =  $("#txt_productName").val();
            ProductDetails.ProductDetail = $("#txt_desc").val();
            ProductDetails.Price= $("#txt_price").val();
            $.ajax({
                url: "http://localhost:24481/api/Product/addProduct",
                type: "Post",
                dataType:'JSON',
                data:ProductDetails, 

                success: function (data) {
                    alert('Updated Successfully');
                    //window.location.href = "../Index";
                },
                error: function (msg) { alert(msg); }
            });
        });
    });
    </script>
<h2>ProductDetails</h2>

<form id="form1" method="post">
    <fieldset>
        <legend>ProductDetails</legend>


        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">

            <input id="txt_productName" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductDetail)
        </div>
        <div class="editor-field">

            <input id="txt_desc" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.ProductDetail)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Price)
        </div>
        <div class="editor-field">

            <input id="txt_price" type="text" name="fname">
            @Html.ValidationMessageFor(model => model.Price)
        </div>



        <p>
            <input id="Save" type="button" value="Create" />
        </p>
    </fieldset>

</form>
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

</form>



@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

How to store printStackTrace into a string

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

Create Word Document using PHP in Linux

PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}

It has an LGPL license and the examples that came with the code worked nicely for me.

JAXB Exception: Class not known to this context

I had the same problem with spring boot. It resolved when i set package to marshaller.

@Bean
public Jaxb2Marshaller marshaller() throws Exception
{
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan("com.octory.ws.dto");
    return marshaller;
}

@Bean
public WebServiceTemplate webServiceTemplate(final Jaxb2Marshaller marshaller)   
{
    WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
    webServiceTemplate.setMarshaller(marshaller);
    webServiceTemplate.setUnmarshaller(marshaller);
    return webServiceTemplate;
}

Should I use `import os.path` or `import os`?

Definitive answer: import os and use os.path. do not import os.path directly.

From the documentation of the module itself:

>>> import os
>>> help(os.path)
...
Instead of importing this module directly, import os and refer to
this module as os.path.  The "os.path" name is an alias for this
module on Posix systems; on other systems (e.g. Mac, Windows),
os.path provides the same operations in a manner specific to that
platform, and is an alias to another module (e.g. macpath, ntpath).
...

Understanding the main method of python

If you import the module (.py) file you are creating now from another python script it will not execute the code within

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.

This is expanded upon a little more at python.berkely.edu

Passing bash variable to jq

Another way to accomplish this is with the jq "--arg" flag. Using the original example:

#!/bin/sh

#this works ***
projectID=$(cat file.json | jq -r '.resource[] | 
select(.username=="[email protected]") | .id')
echo "$projectID"

[email protected]

# Use --arg to pass the variable to jq. This should work:
projectID=$(cat file.json | jq --arg EMAILID $EMAILID -r '.resource[] 
| select(.username=="$EMAILID") | .id')
echo "$projectID"

See here, which is where I found this solution: https://github.com/stedolan/jq/issues/626

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

How to convert dataframe into time series?

Late to the party, but the tsbox package is designed to perform conversions like this. To convert your data into a ts-object, you can do:

dta <- data.frame(
  Dates = c("3/14/2013", "3/15/2013", "3/18/2013", "3/19/2013"),
  Bajaj_close = c(1854.8, 1850.3, 1812.1, 1835.9),
  Hero_close = c(1669.1, 1684.45, 1690.5, 1645.6)
)

dta
#>       Dates Bajaj_close Hero_close
#> 1 3/14/2013      1854.8    1669.10
#> 2 3/15/2013      1850.3    1684.45
#> 3 3/18/2013      1812.1    1690.50
#> 4 3/19/2013      1835.9    1645.60

library(tsbox)
ts_ts(ts_long(dta))
#> Time Series:
#> Start = 2013.1971293045 
#> End = 2013.21081883954 
#> Frequency = 365.2425 
#>          Bajaj_close Hero_close
#> 2013.197      1854.8    1669.10
#> 2013.200      1850.3    1684.45
#> 2013.203          NA         NA
#> 2013.205          NA         NA
#> 2013.208      1812.1    1690.50
#> 2013.211      1835.9    1645.60

It automatically parses the dates, detects the frequency and makes the missing values at the weekends explicit. With ts_<class>, you can convert the data to any other time series class.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Including non-Python files with setup.py

To accomplish what you're describing will take two steps...

  • The file needs to be added to the source tarball
  • setup.py needs to be modified to install the data file to the source path

Step 1: To add the file to the source tarball, include it in the MANIFEST

Create a MANIFEST template in the folder that contains setup.py

The MANIFEST is basically a text file with a list of all the files that will be included in the source tarball.

Here's what the MANIFEST for my project look like:

  • CHANGELOG.txt
  • INSTALL.txt
  • LICENSE.txt
  • pypreprocessor.py
  • README.txt
  • setup.py
  • test.py
  • TODO.txt

Note: While sdist does add some files automatically, I prefer to explicitly specify them to be sure instead of predicting what it does and doesn't.

Step 2: To install the data file to the source folder, modify setup.py

Since you're looking to add a data file (LICENSE.txt) to the source install folder you need to modify the data install path to match the source install path. This is necessary because, by default, data files are installed to a different location than source files.

To modify the data install dir to match the source install dir...

Pull the install dir info from distutils with:

from distutils.command.install import INSTALL_SCHEMES

Modify the data install dir to match the source install dir:

for scheme in INSTALL_SCHEMES.values():
    scheme['data'] = scheme['purelib']

And, add the data file and location to setup():

data_files=[('', ['LICENSE.txt'])]

Note: The steps above should accomplish exactly what you described in a standard manner without requiring any extension libraries.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

I had this problem and its because I wasnt using the latest version of C# (C# 7.3 as of writing this) and I had to change the below internal access modifier to public.

internal class Program
 {
    public static void Main(string[] args)
    {
        //My Code
    }
  }

or ammend the .csproj to use the latest version of C# (this way meant I could still keep the above class as internal):

<PropertyGroup>
    <LangVersion>latest</LangVersion>
    <NoWin32Manifest>true</NoWin32Manifest>
</PropertyGroup>

How to filter keys of an object with lodash?

Just change filter to omitBy

_x000D_
_x000D_
const data = { aaa: 111, abb: 222, bbb: 333 };_x000D_
const result = _.omitBy(data, (value, key) => !key.startsWith("a"));_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

How to trigger click on page load?

$(function(){

    $(selector).click();

});

How do I create a nice-looking DMG for Mac OS X using command-line tools?

Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.

Here's how I'm doing it for a long time, very successfully:

  1. Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).

  2. Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that (see FileStorm link at the bottom for a good tool). The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).

  3. Unmount the DMG again, all settings should be stored by now.

  4. Write a create DMG script, that works as follows:

    • It copies the DMG, so the original one is never touched again.
    • It mounts the copy.
    • It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use mv or ditto for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).
    • After replacing the files, make the script unmount the DMG copy again.
    • Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.

This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).

Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a relase DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).

Regarding the initial layout of the template, FileStorm is a good tool for doing it. It is commercial, but very powerful and easy to use. The normal version is less than $20, so it is really affordable. Maybe one can automate FileStorm to create a DMG (e.g. via AppleScript), never tried that, but once you have found the perfect template DMG, it's really easy to update it for every release.

Linking a UNC / Network drive on an html page

To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).

file://///server/path/to/file.txt

Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:

For security purposes, Mozilla applications block links to local files (and directories) from remote files.

And less directly, from Google:

Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.

The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.

Using iFrames In ASP.NET

You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.

You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server') on the final HTML page that your webform produces when requested.

And you can load a URL into your iframe that is a .aspx page.

But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.

Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?

Passing arrays as url parameter

 <?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";

$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?> 

print $str . "\n"; gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";} and

print $strenc . "\n"; gives

a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D

So if you want to pass this $array through URL to page_no_2.php,

ex:-

$url ='http://page_no_2.php?data=".$strenc."';

To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:

    <?php
    $strenc2= $_GET['data'];
    $arr = unserialize(urldecode($strenc2));
    var_dump($arr);
    ?>

gives

 array(4) {
  ["a"]=>
  string(8) "Thusitha"
  ["b"]=>
  string(10) "Sumanadasa"
  ["c"]=>
  string(6) "Lakmal"
  ["d"]=>
  string(11) "Nanayakkara"
}

again :D

curl: (6) Could not resolve host: google.com; Name or service not known

Issues were:

  1. IPV6 enabled
  2. Wrong DNS server

Here is how I fixed it:

IPV6 Disabling

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cd /etc/modprobe.d/ to change directory to /etc/modprobe.d/
  • Type vi disableipv6.conf to create a new file there
  • Press Esc + i to insert data to file
  • Type install ipv6 /bin/true on the file to avoid loading IPV6 related modules
  • Type Esc + : and then wq for save and exit
  • Type reboot to restart fedora
  • After reboot open terminal and type lsmod | grep ipv6
  • If no result, it means you properly disabled IPV6

Add Google DNS server

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cat /etc/resolv.conf to check what DNS server your Fedora using. Mostly this will be your Modem IP address.
  • Now we have to Find a powerful DNS server. Luckily there is a open DNS server maintain by Google.
  • Go to this page and find out what are the "Google Public DNS IP addresses"
  • Today those are 8.8.8.8 and 8.8.4.4. But in future those may change.
  • Type vi /etc/resolv.conf to edit the resolv.conf file
  • Press Esc + i for insert data to file
  • Comment all the things in the file by inserting # at the begin of the each line. Do not delete anything because can be useful in future.
  • Type below two lines in the file

    nameserver 8.8.8.8
    nameserver 8.8.4.4

    -Type Esc + : and then wq for save and exit

  • Now you are done and everything works fine (Not necessary to restart).
  • But every time when you restart the computer your /etc/resolv.conf will be replaced by default. So I'll let you find a way to avoid that.

Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

I was brought here by a different problem. Whenever I tried to login, i got that message because instead of authenticating correctly I logged in as anonymous user. The solution to my problem was:

To see which user you are, and whose permissions you have:

select user(), current_user();

To delete the pesky anonymous user:

drop user ''@'localhost';

TempData keep() vs peek()

TempData is also a dictionary object that stays for the time of an HTTP Request. So, TempData can be used to maintain data between one controller action to the other controller action.

TempData is used to check the null values each time. TempData contain two method keep() and peek() for maintain data state from one controller action to others.

When TempDataDictionary object is read, At the end of request marks as deletion to current read object.

The keep() and peek() method is used to read the data without deletion the current read object.

You can use Peek() when you always want to hold/prevent the value for another request. You can use Keep() when prevent/hold the value depends on additional logic.

Overloading in TempData.Peek() & TempData.Keep() as given below.

TempData.Keep() have 2 overloaded methods.

  1. void keep() : That menace all the data not deleted on current request completion.

  2. void keep(string key) : persist the specific item in TempData with help of name.

TempData.Peek() no overloaded methods.

  1. object peek(string key) : return an object that contain items with specific key without making key for deletion.

Example for return type of TempData.Keep() & TempData.Peek() methods as given below.

public void Keep(string key) { _retainedKeys.Add(key); }

public object Peek(string key) { object value = values; return value; }

Batch File; List files in directory, only filenames?

The full command is:

dir /b /a-d

Let me break it up;

Basically the /b is what you look for.

/a-d will exclude the directory names.


For more information see dir /? for other arguments that you can use with the dir command.

How to exit from the application and show the home screen?

Add following lines after finish(); in onDestroy():

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();

What is an API key?

An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.

The service maintains all the issued keys and checks them at each request.

By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.

req.query and req.param in ExpressJS

Passing params

GET request to "/cars/honda" 

returns a list of Honda car models

Passing query

GET request to "/car/honda?color=blue"

returns a list of Honda car models, but filtered so only models with an stock color of blue are returned.

It doesn't make sense to add those filters into the URL parameters (/car/honda/color/blue) because according to REST, that would imply that we want to get a bunch of information about the color "blue". Since what we really want is a filtered list of Honda models, we use query strings to filter down the results that get returned.

Notice that the query strings are really just { key: value } pairs in a slightly different format: ?key1=value1&key2=value2&key3=value3.

how to copy only the columns in a DataTable to another DataTable?

DataTable.Clone() should do the trick.

DataTable newTable = originalTable.Clone();

Datatable select with multiple conditions

Do you have to use DataTable.Select()? I prefer to write a linq query for this kind of thing.

var dValue=  from row in myDataTable.AsEnumerable()
             where row.Field<int>("A") == 1 
                   && row.Field<int>("B") == 2 
                   && row.Field<int>("C") == 3
             select row.Field<string>("D");

Rename Files and Directories (Add Prefix)

This will prefix your files in their directory.

The ${f%/*} is the path till the last slash / -> the directory

The ${f##*/} is the text without anything before last slash / -> filename without the path

So that's how it goes:

for f in $(find /directory/ -type f); do 
  mv -v $f ${f%/*}/$(date +%Y%m%d)_Prefix_${f##*/}
done

Remove whitespaces inside a string in javascript

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

Show ImageView programmatically

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

Why are these new categories needed? Are the WG21 gods just trying to confuse us mere mortals?

I don't feel that the other answers (good though many of them are) really capture the answer to this particular question. Yes, these categories and such exist to allow move semantics, but the complexity exists for one reason. This is the one inviolate rule of moving stuff in C++11:

Thou shalt move only when it is unquestionably safe to do so.

That is why these categories exist: to be able to talk about values where it is safe to move from them, and to talk about values where it is not.

In the earliest version of r-value references, movement happened easily. Too easily. Easily enough that there was a lot of potential for implicitly moving things when the user didn't really mean to.

Here are the circumstances under which it is safe to move something:

  1. When it's a temporary or subobject thereof. (prvalue)
  2. When the user has explicitly said to move it.

If you do this:

SomeType &&Func() { ... }

SomeType &&val = Func();
SomeType otherVal{val};

What does this do? In older versions of the spec, before the 5 values came in, this would provoke a move. Of course it does. You passed an rvalue reference to the constructor, and thus it binds to the constructor that takes an rvalue reference. That's obvious.

There's just one problem with this; you didn't ask to move it. Oh, you might say that the && should have been a clue, but that doesn't change the fact that it broke the rule. val isn't a temporary because temporaries don't have names. You may have extended the lifetime of the temporary, but that means it isn't temporary; it's just like any other stack variable.

If it's not a temporary, and you didn't ask to move it, then moving is wrong.

The obvious solution is to make val an lvalue. This means that you can't move from it. OK, fine; it's named, so its an lvalue.

Once you do that, you can no longer say that SomeType&& means the same thing everwhere. You've now made a distinction between named rvalue references and unnamed rvalue references. Well, named rvalue references are lvalues; that was our solution above. So what do we call unnamed rvalue references (the return value from Func above)?

It's not an lvalue, because you can't move from an lvalue. And we need to be able to move by returning a &&; how else could you explicitly say to move something? That is what std::move returns, after all. It's not an rvalue (old-style), because it can be on the left side of an equation (things are actually a bit more complicated, see this question and the comments below). It is neither an lvalue nor an rvalue; it's a new kind of thing.

What we have is a value that you can treat as an lvalue, except that it is implicitly moveable from. We call it an xvalue.

Note that xvalues are what makes us gain the other two categories of values:

  • A prvalue is really just the new name for the previous type of rvalue, i.e. they're the rvalues that aren't xvalues.

  • Glvalues are the union of xvalues and lvalues in one group, because they do share a lot of properties in common.

So really, it all comes down to xvalues and the need to restrict movement to exactly and only certain places. Those places are defined by the rvalue category; prvalues are the implicit moves, and xvalues are the explicit moves (std::move returns an xvalue).

Saving image to file

You could try to save the image using this approach

SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
   int width = Convert.ToInt32(drawImage.Width); 
   int height = Convert.ToInt32(drawImage.Height); 
   Bitmap bmp = new Bitmap(width,height);        
   drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height);
   bmp.Save(dialog.FileName, ImageFormat.Jpeg);
}

Difference between F5, Ctrl + F5 and click on refresh button?

F5 triggers a standard reload.

Ctrl + F5 triggers a forced reload. This causes the browser to re-download the page from the web server, ensuring that it always has the latest copy.

Unlike with F5, a forced reload does not display a cached copy of the page.

How do I test if a string is empty in Objective-C?

check this :

if ([yourString isEqualToString:@""])
{
    NsLog(@"Blank String");
}

Or

if ([yourString length] == 0)
{
    NsLog(@"Blank String");
}

Hope this will help.

How to prevent a browser from storing passwords

I solved this by adding autocomplete="one-time-code" to the password input.

As per an HTML reference autocomplete="one-time-code" - a one-time code used for verifying user identity. It looks like the best fit for this.

How can I remove an SSH key?

The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg which apparently contained the cached keys and profiles.

After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.

I didn't have success with the other approaches.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

How to utilize date add function in Google spreadsheet?

You can use the DATE(Year;Month;Day) to make operations on date:

Examples:

=DATE(2013;3;8 + 30) give the result...  7 april 2013 !
=DATE(2013;3 + 15; 8) give the result... 8 june 2014 !

It's very surprising but it works...

Delete duplicate elements from an array

It's easier using Array.filter:

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

Can't access RabbitMQ web management interface after fresh install

If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:

  1. Go to the RabbitMQ command prompt.

  2. Type:

    rabbitmq-plugins enable rabbitmq_management
    

PHP function to generate v4 UUID

Having searched for the exact same thing and almost implementing a version of this myself, I thought it was worth mentioning that, if you're doing this within a WordPress framework, WP has its own super-handy function for exactly this:

$myUUID = wp_generate_uuid4();

You can read the description and the source here.

How to initialize an array of custom objects

The simplest way to initialize an array

Create array

$array = @()

Create your header

$line = "" | select name,age,phone

Fill the line

$line.name = "Leandro"
$line.age = "39"
$line.phone = "555-555555"

Add line to $array

$array += $line

Result

$array

name                                                     age                                                      phone
----                                                     ---                                                      -----
Leandro                                                  39                                                       555-555555

JavaScript is in array

Just use for your taste:

_x000D_
_x000D_
var blockedTile = [118, 67, 190, 43, 135, 520];_x000D_
_x000D_
// includes (js)_x000D_
_x000D_
if ( blockedTile.includes(118) ){_x000D_
    console.log('Found with "includes"');_x000D_
}_x000D_
_x000D_
// indexOf (js)_x000D_
_x000D_
if ( blockedTile.indexOf(67) !== -1 ){_x000D_
    console.log('Found with "indexOf"');_x000D_
}_x000D_
_x000D_
// _.indexOf (Underscore library)_x000D_
_x000D_
if ( _.indexOf(blockedTile, 43, true) ){_x000D_
    console.log('Found with Underscore library "_.indexOf"');_x000D_
}_x000D_
_x000D_
// $.inArray (jQuery library)_x000D_
_x000D_
if ( $.inArray(190, blockedTile) !== -1 ){_x000D_
    console.log('Found with jQuery library "$.inArray"');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Getting Git to work with a proxy server - fails with "Request timed out"

an alternative to using a proxy is to use SSH In the git configs, configure the origin remote on the ssh address.Then use the ssh-keygen command, which gives you a public key that you can set in your GitLab or Gitab account settings and login accordingly done...

1-verify which remotes are using by running git remote -v in your Git client.

2-if this is http(s) url ,changed it to ssh address , run: git remote set-url <remote name, e.g. origin> <new SSH URL>

3-to generate ssh key for login ,run : ssh-keygen -o, this command generate public(id_rsa.pub file) and private keys.

4-copy public key contents. (from id_rsa.pub file)

5-go to gitlab/githup/.... in profile in setting . create new ssh key and paste public key contents

How do I get a platform-dependent new line character?

If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.

Bootstrap NavBar with left, center or right aligned items

I found the following was a better solution depending on the content of your left, center and right items. A width of 100% without a margin caused overlapping of divs and was preventing anchor tags to work correctly - that is without the messy use of z-indexes.

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    margin: auto;
    margin-left: 48%;
}

How to enable scrolling on website that disabled scrolling?

What worked for me was disabling the position: fixed; CSS.

How to specify the JDK version in android studio?

This is old question but still my answer may help someone

For checking Java version in android studio version , simply open Terminal of Android Studio and type

java -version 

This will display java version installed in android studio

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

PHP find difference between two datetimes

John Conde does all the right procedures in his method but doesn't satisfy the final step in your question which is to format the result to your specifications.

This code (Demo) will display the raw difference, expose the trouble with trying to immediately format the raw difference, display my preparation steps, and finally present the correctly formatted result:

$datetime1 = new DateTime('2017-04-26 18:13:06');
$datetime2 = new DateTime('2011-01-17 17:13:00');  // change the millenium to see output difference
$diff = $datetime1->diff($datetime2);

// this will get you very close, but it will not pad the digits to conform with your expected format
echo "Raw Difference: ",$diff->format('%y years %m months %d days %h hours %i minutes %s seconds'),"\n";

// Notice the impact when you change $datetime2's millenium from '1' to '2'
echo "Invalid format: ",$diff->format('%Y-%m-%d %H:%i:%s'),"\n";  // only H does it right

$details=array_intersect_key((array)$diff,array_flip(['y','m','d','h','i','s']));

echo '$detail array: ';
var_export($details);
echo "\n";

array_map(function($v,$k)
    use(&$r)
    {
        $r.=($k=='y'?str_pad($v,4,"0",STR_PAD_LEFT):str_pad($v,2,"0",STR_PAD_LEFT));
        if($k=='y' || $k=='m'){$r.="-";}
        elseif($k=='d'){$r.=" ";}
        elseif($k=='h' || $k=='i'){$r.=":";}
    },$details,array_keys($details)
);
echo "Valid format: ",$r; // now all components of datetime are properly padded

Output:

Raw Difference: 6 years 3 months 9 days 1 hours 0 minutes 6 seconds
Invalid format: 06-3-9 01:0:6
$detail array: array (
  'y' => 6,
  'm' => 3,
  'd' => 9,
  'h' => 1,
  'i' => 0,
  's' => 6,
)
Valid format: 0006-03-09 01:00:06

Now to explain my datetime value preparation:

$details takes the diff object and casts it as an array. array_flip(['y','m','d','h','i','s']) creates an array of keys which will be used to remove all irrelevant keys from (array)$diff using array_intersect_key().

Then using array_map() my method iterates each value and key in $details, pads its left side to the appropriate length with 0's, and concatenates the $r (result) string with the necessary separators to conform with requested datetime format.

How to enable CORS in AngularJs

Apache/HTTPD tends to be around in most enterprises or if you're using Centos/etc at home. So, if you have that around, you can do a proxy very easily to add the necessary CORS headers.

I have a blog post on this here as I suffered with it quite a few times recently. But the important bit is just adding this to your /etc/httpd/conf/httpd.conf file and ensuring you are already doing "Listen 80":

<VirtualHost *:80>
    <LocationMatch "/SomePath">
       ProxyPass http://target-ip:8080/SomePath
       Header add "Access-Control-Allow-Origin" "*"
    </LocationMatch>
</VirtualHost>

This ensures that all requests to URLs under your-server-ip:80/SomePath route to http://target-ip:8080/SomePath (the API without CORS support) and that they return with the correct Access-Control-Allow-Origin header to allow them to work with your web-app.

Of course you can change the ports and target the whole server rather than SomePath if you like.

Remove "Using default security password" on Spring Boot

Although it works, the current solution is a little overkill as noted in some comments. So here is an alternative that works for me, using the latest Spring Boot (1.4.3).

The default security password is configured inside Spring Boot's AuthenticationManagerConfiguration class. This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.

The folllowing code works to prevent execution of the code inside AuthenticationManagerConfiguration because we define our current AuthenticationManager as a bean.

@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfig extends WebSecurityConfigurerAdapter{

[...]

@Override
protected void configure(AuthenticationManagerBuilder authManager) throws Exception {
    // This is the code you usually have to configure your authentication manager.
    // This configuration will be used by authenticationManagerBean() below.
}

@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    // ALTHOUGH THIS SEEMS LIKE USELESS CODE,
    // IT'S REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
    return super.authenticationManagerBean();
}

}

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.


Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

How to write lists inside a markdown table?

An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.

This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:

---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---

::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}

1. any
2. normal markdown
3. can go in a cell

:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}

some text
:::
::::
:::: {.trow bypara=true}
If bypara=true

Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::

Looks like:

enter image description here

Where does Java's String constant pool live, the heap or the stack?

As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.

It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931

And in Java 8 Hotspot, Permanent Generation has been completely removed.

How can I split a string with a string delimiter?

You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.


You can also use regular expression. A simple google search turned out with this

using System;
using System.Text.RegularExpressions;

class Program {
  static void Main() {
    string value = "cat\r\ndog\r\nanimal\r\nperson";
    // Split the string on line breaks.
    // ... The return value from Split is a string[] array.
    string[] lines = Regex.Split(value, "\r\n");

    foreach (string line in lines) {
        Console.WriteLine(line);
    }
  }
}

Changing minDate and maxDate on the fly using jQuery DatePicker

For from / to date, here is how I implemented restricting the dates based on the date entered in the other datepicker. Works pretty good:

function activateDatePickers() {
    $("#aDateFrom").datepicker({
        onClose: function() {
            $("#aDateTo").datepicker(
                    "change",
                    { minDate: new Date($('#aDateFrom').val()) }
            );
        }
    });
    $("#aDateTo").datepicker({
        onClose: function() {
            $("#aDateFrom").datepicker(
                    "change",
                    { maxDate: new Date($('#aDateTo').val()) }
            );
        }
    });
}

How to achieve ripple animation using support library?

Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"

Update

If you want ripple effect with rounded corners and custom background you can use this:

background_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
<item android:id="@android:id/mask">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

<item android:id="@android:id/background">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

layout.xml

<Button
    android:id="@+id/btn_play"
    android:background="@drawable/background_ripple"
    app:backgroundTint="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/play_now" />

I used this on API >= 21

Getting data-* attribute for onclick event for an html element

I simply use this jQuery trick:

$("a:focus").attr('data-id');

It gets the focused a element and gets the data-id attribute from it.

python capitalize first letter only

a one-liner: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

'Source code does not match the bytecode' when debugging on a device

You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.

How to cin to a vector

These were two methods I tried. Both are fine to use.

int main() {
       
        int size,temp;
        cin>>size;
        vector<int> ar(size);
    //method 1 
      for(auto i=0;i<size;i++)
          {   cin>>temp;
              ar.insert(ar.begin()+i,temp);
          }
          for (auto i:ar) 
            cout <<i<<" "; 
            
     //method 2
     for(int i=0;i<size;i++)
     {
        cin>>ar[i];
     }
     
     for (auto i:ar) 
            cout <<i<<" "; 
        return 0;
    }

How can I sort a std::map first by value, then by key?

std::map will sort its elements by keys. It doesn't care about the values when sorting.

You can use std::vector<std::pair<K,V>> then sort it using std::sort followed by std::stable_sort:

std::vector<std::pair<K,V>> items;

//fill items

//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);

//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);

The first sort should use std::sort since it is nlog(n), and then use std::stable_sort which is n(log(n))^2 in the worst case.

Note that while std::sort is chosen for performance reason, std::stable_sort is needed for correct ordering, as you want the order-by-value to be preserved.


@gsf noted in the comment, you could use only std::sort if you choose a comparer which compares values first, and IF they're equal, sort the keys.

auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b) 
{ 
     return a.second != b.second?  a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);

That should be efficient.

But wait, there is a better approach: store std::pair<V,K> instead of std::pair<K,V> and then you don't need any comparer at all — the standard comparer for std::pair would be enough, as it compares first (which is V) first then second which is K:

std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());

That should work great.

TypeError: no implicit conversion of Symbol into Integer

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

if i.class == Hash

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

end

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Conditionally hide CommandField or ButtonField in Gridview

Hide the Entire GridView Column

If you want to remove the column completely (i.e. not just the button) from the table then use a suitable event handler, e.g. for the OnDataBound event, and then hide the appropriate column on the target GridView. Pick an event that will only fire once for this control, i.e. not OnRowDataBound.

aspx:

<asp:GridView ID="grdUsers" runat="server" DataSourceID="dsProjectUsers" OnDataBound="grdUsers_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Admin Actions">
            <ItemTemplate><asp:Button ID="btnEdit" runat="server" text="Edit" /></ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
        <asp:BoundField DataField="Telephone" HeaderText="Telephone" />
    </Columns>
</asp:GridView>

aspx.cs:

protected void grdUsers_DataBound(object sender, EventArgs e)
{
    try
    {
        // in this case hiding the first col if not admin
        if (!User.IsInRole(Constants.Role_Name_Admin))
            grdUsers.Columns[0].Visible = false;
    }
    catch (Exception ex)
    {
        // deal with ex
    }
}

jQuery ui datepicker with Angularjs

As a best practice, especially if you have multiple date pickers, you should not hardcode the element's scope variable name.

Instead, you should get the clicked input's ng-model and update its corresponding scope variable inside the onSelect method.

app.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            $(element).datepicker({
                dateFormat: 'yy-mm-dd',

                onSelect: function(date) {
                    var ngModelName = this.attributes['ng-model'].value;

                    // if value for the specified ngModel is a property of 
                    // another object on the scope
                    if (ngModelName.indexOf(".") != -1) {
                        var objAttributes = ngModelName.split(".");
                        var lastAttribute = objAttributes.pop();
                        var partialObjString = objAttributes.join(".");
                        var partialObj = eval("scope." + partialObjString);

                        partialObj[lastAttribute] = date;
                    }
                    // if value for the specified ngModel is directly on the scope
                    else {
                        scope[ngModelName] = date;
                    }
                    scope.$apply();
                }

            });
        }
    };
});

EDIT

To address the issue that @Romain raised up (Nested Elements), I have modified my answer

How to Get Element By Class in JavaScript?

I think something like:

function ReplaceContentInContainer(klass,content) {
var elems = document.getElementsByTagName('*');
for (i in elems){
    if(elems[i].getAttribute('class') == klass || elems[i].getAttribute('className') == klass){
        elems[i].innerHTML = content;
    }
}
}

would work

how do I set height of container DIV to 100% of window height?

You can net set it to view height

html, body
{
    height: 100vh;
}

How to implement a lock in JavaScript

Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.

I suspect you need to just set a semaphore (flagging system) between your buttons.

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

How to find the .NET framework version of a Visual Studio project?

  • VB

Project Properties -> Compiler Tab -> Advanced Compile Options button

  • C#

Project Properties -> Application Tab

Access localhost from the internet

Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.

THen, send your ip + port to the person who will use it.

sample: http://200.200.200.200:8080/mySite/

VSCode: How to Split Editor Vertically

In version 1.23.1, it is Ctrl+Shift+P and Split Editor This will divide the screens vertically and you can move through them using Ctrl+K+LeftArrow

Screenshot of the Split Editor

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

Descending order by date filter in AngularJs

And a code example:

<div ng-app>
    <div ng-controller="FooController">
        <ul ng-repeat="item in items | orderBy:'num':true">
            <li>{{item.num}} :: {{item.desc}}</li>
        </ul>
    </div>
</div>

And the JavaScript:

function FooController($scope) {
    $scope.items = [
        {desc: 'a', num: 1},
        {desc: 'b', num: 2},
        {desc: 'c', num: 3},
    ];
}

Will give you:

3 :: c
2 :: b
1 :: a

On JSFiddle: http://jsfiddle.net/agjqN/

Sort Pandas Dataframe by Date

You can use pd.to_datetime() to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.

>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
    'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
         Date Symbol
0  02/20/2015      A
1  01/15/2016      A
2  08/21/2015      A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

For future search, you can change the sort statement:

>>> df.sort_values(by='Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

What characters are allowed in an email address?

The accepted answer refers to a Wikipedia article when discussing the valid local-part of an email address, but Wikipedia is not an authority on this.

IETF RFC 3696 is an authority on this matter, and should be consulted at section 3. Restrictions on email addresses on page 5:

Contemporary email addresses consist of a "local part" separated from a "domain part" (a fully-qualified domain name) by an at-sign ("@"). The syntax of the domain part corresponds to that in the previous section. The concerns identified in that section about filtering and lists of names apply to the domain names used in an email context as well. The domain name can also be replaced by an IP address in square brackets, but that form is strongly discouraged except for testing and troubleshooting purposes.

The local part may appear using the quoting conventions described below. The quoted forms are rarely used in practice, but are required for some legitimate purposes. Hence, they should not be rejected in filtering routines but, should instead be passed to the email system for evaluation by the destination host.

The exact rule is that any ASCII character, including control characters, may appear quoted, or in a quoted string. When quoting is needed, the backslash character is used to quote the following character. For example

  Abc\@[email protected]

is a valid form of an email address. Blank spaces may also appear, as in

  Fred\ [email protected]

The backslash character may also be used to quote itself, e.g.,

  Joe.\\[email protected]

In addition to quoting using the backslash character, conventional double-quote characters may be used to surround strings. For example

  "Abc@def"@example.com

  "Fred Bloggs"@example.com

are alternate forms of the first two examples above. These quoted forms are rarely recommended, and are uncommon in practice, but, as discussed above, must be supported by applications that are processing email addresses. In particular, the quoted forms often appear in the context of addresses associated with transitions from other systems and contexts; those transitional requirements do still arise and, since a system that accepts a user-provided email address cannot "know" whether that address is associated with a legacy system, the address forms must be accepted and passed into the email environment.

Without quotes, local-parts may consist of any combination of
alphabetic characters, digits, or any of the special characters

  ! # $ % & ' * + - / = ?  ^ _ ` . { | } ~

period (".") may also appear, but may not be used to start or end the local part, nor may two or more consecutive periods appear. Stated differently, any ASCII graphic (printing) character other than the at-sign ("@"), backslash, double quote, comma, or square brackets may appear without quoting. If any of that list of excluded characters are to appear, they must be quoted. Forms such as

  [email protected]

  customer/[email protected]

  [email protected]

  !def!xyz%[email protected]

  [email protected]

are valid and are seen fairly regularly, but any of the characters listed above are permitted.

As others have done, I submit a regex that works for both PHP and JavaScript to validate email addresses:

/^[a-z0-9!'#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!'#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-zA-Z]{2,}$/i

Find out free space on tablespace

Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.

I think the code below does that. It calculates free space as "freespace" + unallocated space.

select 
     free.tablespace_name,
     free.bytes,
     reserv.maxbytes,
     reserv.bytes,
     reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
     reserv.datafiles
from
    (select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
    (select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

System.Timers.Timer vs System.Threading.Timer

One important difference not mentioned above which might catch you out is that System.Timers.Timer silently swallows exceptions, whereas System.Threading.Timer doesn't.

For example:

var timer = new System.Timers.Timer { AutoReset = false };
timer.Elapsed += (sender, args) =>
{
    var z = 0;
    var i = 1 / z;
};
timer.Start();

vs

var timer = new System.Threading.Timer(x =>
{
    var z = 0;
    var i = 1 / z;
}, null, 0, Timeout.Infinite);

Retrieve the commit log for a specific line in a file?

Try using below command implemented in Git 1.8.4.

git log -u -L <upperLimit>,<lowerLimit>:<path_to_filename>

So, in your case upperLimit & lowerLimit is the touched line_number

More info - https://www.techpurohit.com/list-some-useful-git-commands

How to get TimeZone from android mobile?

TimeZone timeZone = TimeZone.getDefault(); 
timeZone.getID();

It will print like

Asia/Kolkata

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

How do I use LINQ Contains(string[]) instead of Contains(string)

from xx in table
where xx.uid.Split(',').Contains(string value )
select xx

Setting a PHP $_SESSION['var'] using jQuery

Might want to try putting the PHP function on another PHP page, and use an AJAX call to set the variable.

jQuery: Wait/Delay 1 second without executing code

You can also just delay some operation this way:

setTimeout(function (){

  // Something you want delayed.

}, 5000); // How long do you want the delay to be (in milliseconds)? 

How can I listen for a click-and-hold in jQuery?

I wrote some code to make it easy

_x000D_
_x000D_
//Add custom event listener_x000D_
$(':root').on('mousedown', '*', function() {_x000D_
    var el = $(this),_x000D_
        events = $._data(this, 'events');_x000D_
    if (events && events.clickHold) {_x000D_
        el.data(_x000D_
            'clickHoldTimer',_x000D_
            setTimeout(_x000D_
                function() {_x000D_
                    el.trigger('clickHold')_x000D_
                },_x000D_
                el.data('clickHoldTimeout')_x000D_
            )_x000D_
        );_x000D_
    }_x000D_
}).on('mouseup mouseleave mousemove', '*', function() {_x000D_
    clearTimeout($(this).data('clickHoldTimer'));_x000D_
});_x000D_
_x000D_
//Attach it to the element_x000D_
$('#HoldListener').data('clickHoldTimeout', 2000); //Time to hold_x000D_
$('#HoldListener').on('clickHold', function() {_x000D_
    console.log('Worked!');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<img src="http://lorempixel.com/400/200/" id="HoldListener">
_x000D_
_x000D_
_x000D_

See on JSFiddle

Now you need just to set the time of holding and add clickHold event on your element

Send Post Request with params using Retrofit

You should create an interface for that like it is working well

public interface Service {
    @FormUrlEncoded
    @POST("v1/EmergencyRequirement.php/?op=addPatient")
    Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
           @Field("Address") String Address,
           @Field("City") String city, @Field("ContactNumber") String  contactnumber, 
           @Field("PatientName") String name, 
           @Field("Time") String Time, @Field("DonatedBy") String donar);
}

or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html

and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit

How to break out of while loop in Python?

What I would do is run the loop until the ans is Q

ans=(R)
while not ans=='Q':
    print('Your score is so far '+str(myScore)+'.')
    print("Would you like to roll or quit?")
    ans=input("Roll...")
    if ans=='R':
        R=random.randint(1, 8)
        print("You rolled a "+str(R)+".")
        myScore=R+myScore

Best cross-browser method to capture CTRL+S with JQuery?

$(window).keypress(function(event) {
    if (!(event.which == 115 && event.ctrlKey) && !(event.which == 19)) return true;
    alert("Ctrl-S pressed");
    event.preventDefault();
    return false;
});

Key codes can differ between browsers, so you may need to check for more than just 115.

Get IP address of an interface on Linux

If you're looking for an address (IPv4) of the specific interface say wlan0 then try this code which uses getifaddrs():

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) 
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }


    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) 
    {
        if (ifa->ifa_addr == NULL)
            continue;  

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

        if((strcmp(ifa->ifa_name,"wlan0")==0)&&(ifa->ifa_addr->sa_family==AF_INET))
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host); 
        }
    }

    freeifaddrs(ifaddr);
    exit(EXIT_SUCCESS);
}

You can replace wlan0 with eth0 for ethernet and lo for local loopback.

The structure and detailed explanations of the data structures used could be found here.

To know more about linked list in C this page will be a good starting point.

Do checkbox inputs only post data if they're checked?

Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs

JS:

var chk = $('input[type="checkbox"]');
    chk.each(function(){
        var v = $(this).attr('checked') == 'checked'?1:0;
        $(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
    });

chk.change(function(){ 
        var v = $(this).is(':checked')?1:0;
        $(this).next('input[type="hidden"]').val(v);
    });

HTML:

<label>Active</label><input rel="active" type="checkbox" />

How to clear an ImageView in Android?

Hey i know i am extremely late to this answer, but just thought i must share this,

The method to call when u reset the image must be the same method that u called while u were setting it.

When u want to reset the image source @dennis.sheepard answer works fine only if u are originally setting the image in the bitmap using setImageResource()

for instance,

i had used setImageBitmap() and hence setting setImageResource(0) didn work, instead i used setImageBitmap(null).

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
    ...
    Do SQL stuff here passing my trans into my various SQL executers
    ...
    trans.Commit  // May not be quite right
}

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

How can I remove a trailing newline?

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

or you could always get geekier with regexps :)

have fun!

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

This started happening to me when my database size grew and I was doing a lot of transactions on it.

Truth is there is probably some way to optimize either your queries or your DB but try these 2 queries for a work around fix.

Run this:

SET GLOBAL innodb_lock_wait_timeout = 5000; 

And then this:

SET innodb_lock_wait_timeout = 5000; 

ASP.NET MVC ActionLink and post method

You can't use an ActionLink because that just renders an anchor <a> tag.
You can use a jQuery AJAX post.
Or just call the form's submit method with or without jQuery (which would be non-AJAX), perhaps in the onclick event of whatever control takes your fancy.

How to write a file with C in Linux?

You have to do write in the same loop as read.

Can we open pdf file using UIWebView on iOS?

Swift version:

if let docPath = NSBundle.mainBundle().pathForResource("sample", ofType: "pdf") {
    let docURL = NSURL(fileURLWithPath: docPath)
    webView.loadRequest(NSURLRequest(URL: docURL))
}

Resizing an iframe based on content

Something on the lines of this i belive should work.

parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;

Load this with your body onload on the iframe content.

map function for objects (instead of arrays)

I handle only strings to reduce exemptions:

Object.keys(params).map(k => typeof params[k] == "string" ? params[k] = params[k].trim() : null);

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Why does Oracle not find oci.dll?

I just added the oracle folder to my environmental variables and that fixed my identical error

Share Text on Facebook from Android App via ACTION_SEND

if you want to show text put # at the begging of the message you want it will share it as Hashtag

TypeError: ObjectId('') is not JSON serializable

>>> from bson import Binary, Code
>>> from bson.json_util import dumps
>>> dumps([{'foo': [1, 2]},
...        {'bar': {'hello': 'world'}},
...        {'code': Code("function x() { return 1; }")},
...        {'bin': Binary("")}])
'[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'

Actual example from json_util.

Unlike Flask's jsonify, "dumps" will return a string, so it cannot be used as a 1:1 replacement of Flask's jsonify.

But this question shows that we can serialize using json_util.dumps(), convert back to dict using json.loads() and finally call Flask's jsonify on it.

Example (derived from previous question's answer):

from bson import json_util, ObjectId
import json

#Lets create some dummy document to prove it will work
page = {'foo': ObjectId(), 'bar': [ObjectId(), ObjectId()]}

#Dump loaded BSON to valid JSON string and reload it as dict
page_sanitized = json.loads(json_util.dumps(page))
return page_sanitized

This solution will convert ObjectId and others (ie Binary, Code, etc) to a string equivalent such as "$oid."

JSON output would look like this:

{
  "_id": {
    "$oid": "abc123"
  }
}

doGet and doPost in Servlets

If you do <form action="identification" > for your html form, data will be passed using 'Get' by default and hence you can catch this using doGet function in your java servlet code. This way data will be passed under the HTML header and hence will be visible in the URL when submitted. On the other hand if you want to pass data in HTML body, then USE Post: <form action="identification" method="post"> and catch this data in doPost function. This was, data will be passed under the html body and not the html header, and you will not see the data in the URL after submitting the form.

Examples from my html:

<body>  
<form action="StartProcessUrl" method="post">
.....
.....

Examples from my java servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
         String surname = request.getParameter("txtSurname");
         String firstname = request.getParameter("txtForename");
         String rqNo = request.getParameter("txtRQ6");
         String nhsNo = request.getParameter("txtNHSNo");

         String attachment1 = request.getParameter("base64textarea1");
         String attachment2 = request.getParameter("base64textarea2");

.........
.........

How to put wildcard entry into /etc/hosts?

Here is the configuration for those trying to accomplish the original goal (wildcards all pointing to same codebase -- install nothing, dev environment ie, XAMPP)

hosts file (add an entry)

file: /etc/hosts (non-windows)

127.0.0.1   example.local

httpd.conf configuration (enable vhosts)

file: /XAMPP/etc/httpd.conf

# Virtual hosts
Include etc/extra/httpd-vhosts.conf

httpd-vhosts.conf configuration

file: XAMPP/etc/extra/httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/path_to_XAMPP/htdocs"
    ServerName example.local
    ServerAlias *.example.local
#    SetEnv APP_ENVIRONMENT development
#    ErrorLog "logs/example.local-error_log"
#    CustomLog "logs/example.local-access_log" common
</VirtualHost>

restart apache

create pac file:

save as whatever.pac wherever you want to and then load the file in the browser's network>proxy>auto_configuration settings (reload if you alter this)

function FindProxyForURL(url, host) {
  if (shExpMatch(host, "*example.local")) {
    return "PROXY example.local";
  }
  return "DIRECT";
}

Creating a Menu in Python

This should do it. You were missing a ) and you only need """ not 4 of them. Also you don't need a elif at the end.

ans=True
while ans:
    print("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ")
    if ans=="1":
      print("\nStudent Added")
    elif ans=="2":
      print("\n Student Deleted")
    elif ans=="3":
      print("\n Student Record Found")
    elif ans=="4":
      print("\n Goodbye") 
      ans = None
    else:
       print("\n Not Valid Choice Try again")

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

How to change a <select> value from JavaScript

this solved my issue, it was working fine with

var value = item[index].id;
$("#select2").val(value);

but not showing selected value, so

$("#select2").val(value).change();

works fine for me.

How to echo (or print) to the js console with php

There are much better ways to print variable's value in PHP. One of them is to use buildin var_dump() function. If you want to use var_dump(), I would also suggest to install Xdebug (from https://xdebug.org) since it generates much more readable printouts.

The idea of printing values to browser console is somewhat bizarre, but if you really want to use it, there is very useful Google Chrome extension, PHP Console, which should satisfy all your needs. You can find it at consle.com It works well also in Vivaldi and in Opera (though you will need "Download Chrome Extension" extension to install it). The extension is accompanied by PHP library you use in your code.

How to create a generic array?

You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.

Arrays are covariant, Generics are not:

What that means? You must be knowing by now that the following assignment is valid:

Object[] arr = new String[10];

Basically, an Object[] is a super type of String[], because Object is a super type of String. This is not true with generics. So, the following declaration is not valid, and won't compile:

List<Object> list = new ArrayList<String>(); // Will not compile.

Reason being, generics are invariant.

Enforcing Type Check:

Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String> has a static type of List<String> but a dynamic type of List.

However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:

Object[] arr = new String[10];
arr[0] = new Integer(10);

will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.

So, what's the issue with Generic Array Creation?

Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.

Consider the code as below:

public <T> T[] getArray(int size) {
    T[] arr = new T[size];  // Suppose this was allowed for the time being.
    return arr;
}

Since the type of T is not known at runtime, the array created is actually an Object[]. So the above method at runtime will look like:

public Object[] getArray(int size) {
    Object[] arr = new Object[size];
    return arr;
}

Now, suppose you call this method as:

Integer[] arr = getArray(10);

Here's the problem. You have just assigned an Object[] to a reference of Integer[]. The above code will compile fine, but will fail at runtime.

That is why generic array creation is forbidden.

Why typecasting new Object[10] to E[] works?

Now your last doubt, why the below code works:

E[] elements = (E[]) new Object[10];

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

public <T> T[] getArray(int size) {
    T[] arr = (T[])new Object[size];        
    return arr;
}

and you call invoke it like this:

String[] arr = getArray(10);

this will fail at runtime with a ClassCastException. So, no this way will not work always.

What about creating an array of type List<String>[]?

The issue is the same. Due to type erasure, a List<String>[] is nothing but a List[]. So, had the creation of such arrays allowed, let's see what could happen:

List<String>[] strlistarr = new List<String>[10];  // Won't compile. but just consider it
Object[] objarr = strlistarr;    // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.

Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[] and List<Integer>[] are compiled to List[] at runtime.

So can we create array of unbounded wildcard parameterized types?

Yes. The reason being, a List<?> is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.

List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>();  // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine

Both the above case is fine, because List<?> is super type of all the instantiation of the generic type List<E>. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[].

So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null (Ignoring the unbounded types).

Is there any workaround for E[]?

Yes, you can create the array using Array#newInstance() method:

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Typecast is needed because that method returns an Object. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.

jQuery Popup Bubble/Tooltip

I have programmed an useful jQuery Plugin to create easily smart bubble popups with only a line of code in jQuery!

What You can do: - attach popups to any DOM element! - mouseover/mouseout events automatically managed! - set custom popups events! - create smart shadowed popups! (in IE too!) - choose popup’s style templates at runtime! - insert HTML messages inside popups! - set many options as: distances, velocity, delays, colors…

Popup’s shadows and colorized templates are fully supported by Internet Explorer 6+, Firefox, Opera 9+, Safari

You can download sources from http://plugins.jquery.com/project/jqBubblePopup

What is the correct XPath for choosing attributes that contain "foo"?

This XPath will give you all nodes that have attributes containing 'Foo' regardless of node name or attribute name:

//attribute::*[contains(., 'Foo')]/..

Of course, if you're more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..

//attribute::*[contains(., 'Foo')]

Generate war file from tomcat webapp folder

There is a way to create war file of your project from eclipse.

First a create an xml file with the following code,

Replace HistoryCheck with your project name.

<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
    <target name="default" depends="buildwar,deploy"></target>
    <target name="buildwar">
        <war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
            <exclude name="WEB-INF/**" />
            <webinf dir="war/WEB-INF/">
                <include name="**/*.jar" />
            </webinf>
        </war>
    </target>
    <target name="deploy">
        <copy file="HistoryCheck.war" todir="." />
    </target>
</project>

Now, In project explorer right click on that xml file and Run as-> ant build

You can see the war file of your project in your project folder.

Keras, how do I predict after I trained a model?

You can just "call" your model with an array of the correct shape:

model(np.array([[6.7, 3.3, 5.7, 2.5]]))

Full example:

from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np

X, y = load_iris(return_X_y=True)

model = Sequential([
    Dense(16, activation='relu'),
    Dense(32, activation='relu'),
    Dense(1)])

model.compile(loss='mean_absolute_error', optimizer='adam')

history = model.fit(X, y, epochs=10, verbose=0)

print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>

How can I switch word wrap on and off in Visual Studio Code?

Go to menu FilePreferencesUser Settings.

It will open up Default Settings and settings.json automatically. Just add the following in the settings.json file and save it. This will overwrite the default settings.

// Place your settings in this file to overwrite the default settings
{ "editor.wrappingColumn": 0 }

Screenshot of settings being edited.

Laravel 5 call a model function in a blade view

In new version of Laravel you can use "Service Injection".

https://laravel.com/docs/5.8/blade#service-injection

/resources/views/main.blade.php

@inject('project', 'App\Project')

<h1>{{ $project->get_title() }}</h1>

Error in model.frame.default: variable lengths differ

Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

What version of javac built my jar?

Following up on @David J. Liszewski's answer, I ran the following commands to extract the jar file's manifest on Ubuntu:

# Determine the manifest file name:
$ jar tf LuceneSearch.jar | grep -i manifest
META-INF/MANIFEST.MF

# Extract the file:
$ sudo jar xf LuceneSearch.jar META-INF/MANIFEST.MF

# Print the file's contents:
$ more META-INF/MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.7.0_25-b30 (Oracle Corporation)
Main-Class: org.wikimedia.lsearch.config.StartupManager

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

How to find all combinations of coins when given some dollar value

/*
* make a list of all distinct sets of coins of from the set of coins to
* sum up to the given target amount.
* Here the input set of coins is assumed yo be {1, 2, 4}, this set MUST
* have the coins sorted in ascending order.
* Outline of the algorithm:
* 
* Keep track of what the current coin is, say ccn; current number of coins
* in the partial solution, say k; current sum, say sum, obtained by adding
* ccn; sum sofar, say accsum:
*  1) Use ccn as long as it can be added without exceeding the target
*     a) if current sum equals target, add cc to solution coin set, increase
*     coin coin in the solution by 1, and print it and return
*     b) if current sum exceeds target, ccn can't be in the solution, so
*        return
*     c) if neither of the above, add current coin to partial solution,
*        increase k by 1 (number of coins in partial solution), and recuse
*  2) When current denomination can no longer be used, start using the
*     next higher denomination coins, just like in (1)
*  3) When all denominations have been used, we are done
*/

#include <iostream>
#include <cstdlib>

using namespace std;

// int num_calls = 0;
// int num_ways = 0;

void print(const int coins[], int n);

void combine_coins(
                   const int denoms[], // coins sorted in ascending order
                   int n,              // number of denominations
                   int target,         // target sum
                   int accsum,         // accumulated sum
                   int coins[],        // solution set, MUST equal
                                       // target / lowest denom coin
                   int k               // number of coins in coins[]
                  )
{

    int  ccn;   // current coin
    int  sum;   // current sum

    // ++num_calls;

    for (int i = 0; i < n; ++i) {
        /*
         * skip coins of lesser denomination: This is to be efficient
         * and also avoid generating duplicate sequences. What we need
         * is combinations and without this check we will generate
         * permutations.
         */
        if (k > 0 && denoms[i] < coins[k - 1])
            continue;   // skip coins of lesser denomination

        ccn = denoms[i];

        if ((sum = accsum + ccn) > target)
            return;     // no point trying higher denominations now


        if (sum == target) {
            // found yet another solution
            coins[k] = ccn;
            print(coins, k + 1);
            // ++num_ways;
            return;
        }

        coins[k] = ccn;
        combine_coins(denoms, n, target, sum, coins, k + 1);
    }
}

void print(const int coins[], int n)
{
    int s = 0;
    for (int i = 0; i < n; ++i) {
        cout << coins[i] << " ";
        s += coins[i];
    }
    cout << "\t = \t" << s << "\n";

}

int main(int argc, const char *argv[])
{

    int denoms[] = {1, 2, 4};
    int dsize = sizeof(denoms) / sizeof(denoms[0]);
    int target;

    if (argv[1])
        target = atoi(argv[1]);
    else
        target = 8;

    int *coins = new int[target];


    combine_coins(denoms, dsize, target, 0, coins, 0);

    // cout << "num calls = " << num_calls << ", num ways = " << num_ways << "\n";

    return 0;
}

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

Making a button invisible by clicking another button in HTML

try this

function demoShow() {   
document.getElementById("but1").style.display="none";

}



<input type="button" value="click me" onclick="demoShow()" id="but" />

<input type="button" value="hide" id="but1" />

Concatenate columns in Apache Spark DataFrame

Indeed, there are some beautiful inbuilt abstractions for you to accomplish your concatenation without the need to implement a custom function. Since you mentioned Spark SQL, so I am guessing you are trying to pass it as a declarative command through spark.sql(). If so, you can accomplish in a straight forward manner passing SQL command like: SELECT CONCAT(col1, '<delimiter>', col2, ...) AS concat_column_name FROM <table_name>;

Also, from Spark 2.3.0, you can use commands in lines with: SELECT col1 || col2 AS concat_column_name FROM <table_name>;

Wherein, is your preferred delimiter (can be empty space as well) and is the temporary or permanent table you are trying to read from.

onchange event for input type="number"

There may be a better solution, but this is what came to mind:

var value = $("#yourInput").val();
$("#yourInput").on('keyup change click', function () {
    if(this.value !== value) {
        value = this.value;
        //Do stuff
    }        
});

Here's a working example.

It simply binds an event handler to the keyup, change and click events. It checks whether or not the value has changed, and if so, stores the current value so it can check again next time. The check is required to deal with the click event.

Disable Logback in SpringBoot

Add exclusion to both the spring-boot-starter and spring-boot-starter-web to resolve the conflict.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

Why does Git treat this text file as a binary file?

I had an instance where .gitignore contained a double \r (carriage return) sequence by purpose.

That file was identified as binary by git. Adding a .gitattributes file helped.

# .gitattributes file
.gitignore diff

What is the difference between signed and unsigned variables?

Unsigned variables are variables which are internally represented without a mathematical sign (plus or minus) can store 'zero' or positive values only. Let us say the unsigned variable is n bits in size, then it can represent 2^n (2 power n) values - 0 through (2^n -1). A signed variable on the other hand, 'loses' one bit for representing the sign, so it can store values from -(2^(n-1) -1) through (2^(n-1)) including zero. Thus, a signed variable can store positive values, negative values and zero.

P.S.:
Internally, the mathematical sign may be represented in one's complement form, two's complement form or with a sign bit (eg: 0 -> +, 1-> -)
All these methods effectively divide the range of representable values in n bits (2^n) into three parts, positive, negative and zero.

This is just my two cents worth.

I hope this helps.

Making LaTeX tables smaller?

if it's too long for one page, use the longtable package. and if it's too wide for the page, use p{width} in place of l,r, or c for the column specifier. you can also go smaller than \small, i.e. \footnotesize and \tiny. I would consult the setspace package for options on how to remove the double space, though it's probably \singlespace or something like that.

CSS technique for a horizontal line with words in the middle

Ok, this one is more complicated but it works in everything but IE<8

<div><span>text TEXT</span></div>

div {
    text-align: center;
    position: relative;
}
span {
    display: inline-block;    
}
span:before,
span:after {
    border-top: 1px solid black;
    display: block;
    height: 1px;
    content: " ";
    width: 40%;
    position: absolute;
    left: 0;
    top: 1.2em;
}
span:after {
   right: 0;  
   left: auto; 
}

The :before and :after elements are positioned absolutely so we can pull one to the left and one to the right. Also, the width (40% in this case) is very dependent of the width of the text inside.. have to think about a solution for that. At least the top: 1.2em makes sure the lines stay more or less in the center of the text even if you have different font size.

It does seem to work well though: http://jsfiddle.net/tUGrf/3/

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

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

Python: Tuples/dictionaries as keys, select, sort

This type of data is efficiently pulled from a Trie-like data structure. It also allows for fast sorting. The memory efficiency might not be that great though.

A traditional trie stores each letter of a word as a node in the tree. But in your case your "alphabet" is different. You are storing strings instead of characters.

it might look something like this:

root:                Root
                     /|\
                    / | \
                   /  |  \     
fruit:       Banana Apple Strawberry
              / |      |     \
             /  |      |      \
color:     Blue Yellow Green  Blue
            /   |       |       \
           /    |       |        \
end:      24   100      12        0

see this link: trie in python

node.js remove file

Here the code where you can delete file/image from folder.

var fs = require('fs'); 
Gallery.findById({ _id: req.params.id},function(err,data){ 
    if (err) throw err;
    fs.unlink('public/gallery/'+data.image_name);
 });

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Removing empty lines in Notepad++

  1. notepad++
  2. Ctrl-H
  3. Select Regular Expression
  4. Enter ^[ \t]*$\r?\n into find what, leave replace empty. This will match all lines starting with white space and ending with carriage return (in this case a windows crlf)
  5. Click the Find Next button to see for yourself how it matches only empty lines.

jQuery Button.click() event is triggered twice

Related to Stepan's Answer.

in my case, i have both input and label in my .click() listener.

i just replaced the label to div, it worked!

jQuery Set Selected Option Using Next

This is what i just used, i like how clean it is :-)

$('select').val(function(){
    var nextOption = $(this).children(':selected').next();
    return $(nextOption).val();
}).change();

RegEx: Grabbing values between quotation marks

A supplementary answer for the subset of Microsoft VBA coders only one uses the library Microsoft VBScript Regular Expressions 5.5 and this gives the following code

Sub TestRegularExpression()

    Dim oRE As VBScript_RegExp_55.RegExp    '* Tools->References: Microsoft VBScript Regular Expressions 5.5
    Set oRE = New VBScript_RegExp_55.RegExp

    oRE.Pattern = """([^""]*)"""


    oRE.Global = True

    Dim sTest As String
    sTest = """Foo Bar"" ""Another Value"" something else"

    Debug.Assert oRE.test(sTest)

    Dim oMatchCol As VBScript_RegExp_55.MatchCollection
    Set oMatchCol = oRE.Execute(sTest)
    Debug.Assert oMatchCol.Count = 2

    Dim oMatch As Match
    For Each oMatch In oMatchCol
        Debug.Print oMatch.SubMatches(0)

    Next oMatch

End Sub

php search array key and get value

<?php

// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
  echo $search_array[20120504];
}

// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
  echo $search_array[20120504];
}

// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
  echo $search_array[20120504];
}

?>

How do I truncate a .NET string?

I did mine in one line sort of like this

value = value.Length > 1000 ? value.Substring(0, 1000) : value;

Populating VBA dynamic arrays

In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are

  1. Creating an array big enough to handle anything you think will be thrown at it
  2. Sensible use of Redim Preserve

The code below provides an example of a routine that will dimension myArray in line with the lngSize variable, then add additional elements (equal to the initial array size) by use of a Mod test whenever the upper bound is about to be exceeded

Option Base 1

Sub ArraySample()
    Dim myArray() As String
    Dim lngCnt As Long
    Dim lngSize As Long

    lngSize = 10
    ReDim myArray(1 To lngSize)

    For lngCnt = 1 To lngSize*5
        If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
        myArray(lngCnt) = "I am record number " & lngCnt
    Next
End Sub

How to update data in one table from corresponding data in another table in SQL Server 2005

update test1 t1, test2 t2
set t2.deptid = t1.deptid
where t2.employeeid = t1.employeeid

you can not use from keyword for the mysql

Save PL/pgSQL output from PostgreSQL to a CSV file

In terminal (while connected to the db) set output to the cvs file

1) Set field seperator to ',':

\f ','

2) Set output format unaligned:

\a

3) Show only tuples:

\t

4) Set output:

\o '/tmp/yourOutputFile.csv'

5) Execute your query:

:select * from YOUR_TABLE

6) Output:

\o

You will then be able to find your csv file in this location:

cd /tmp

Copy it using the scp command or edit using nano:

nano /tmp/yourOutputFile.csv

Numpy: find index of the elements within range

s=[52, 33, 70, 39, 57, 59, 7, 2, 46, 69, 11, 74, 58, 60, 63, 43, 75, 92, 65, 19, 1, 79, 22, 38, 26, 3, 66, 88, 9, 15, 28, 44, 67, 87, 21, 49, 85, 32, 89, 77, 47, 93, 35, 12, 73, 76, 50, 45, 5, 29, 97, 94, 95, 56, 48, 71, 54, 55, 51, 23, 84, 80, 62, 30, 13, 34]

dic={}

for i in range(0,len(s),10):
    dic[i,i+10]=list(filter(lambda x:((x>=i)&(x<i+10)),s))
print(dic)

for keys,values in dic.items():
    print(keys)
    print(values)

Output:

(0, 10)
[7, 2, 1, 3, 9, 5]
(20, 30)
[22, 26, 28, 21, 29, 23]
(30, 40)
[33, 39, 38, 32, 35, 30, 34]
(10, 20)
[11, 19, 15, 12, 13]
(40, 50)
[46, 43, 44, 49, 47, 45, 48]
(60, 70)
[69, 60, 63, 65, 66, 67, 62]
(50, 60)
[52, 57, 59, 58, 50, 56, 54, 55, 51]  

How can I solve equations in Python?

How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…

How can I concatenate a string and a number in Python?

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9
"asd" + str(9)

Getting query parameters from react-router hash fragment

Note: Copy / Pasted from comment. Be sure to like the original post!

Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:

this.props.location.query

It creates a hash of all available query params in the url.

Update:

For React-Router v4, see this answer. Basically, use this.props.location.search to get the query string and parse with the query-string package or URLSearchParams:

const params = new URLSearchParams(paramsString); 
const tags = params.get('tags');

Function Pointers in Java

You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.

public interface IFunction {
  public void execute(Object o);
}

This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).

public static void doFunc(Collection c, IFunction f) {
   for (Object o : c) {
      f.execute(o);
   }
}

As an example say we have a collection of numbers and you would like to add 1 to every element.

CollectionUtils2.doFunc(List numbers, new IFunction() {
    public void execute(Object o) {
       Integer anInt = (Integer) o;
       anInt++;
    }
});

Node Version Manager (NVM) on Windows

First off, I use nvm on linux machine.

When looking at the documentation for nvm at https://www.npmjs.org/package/nvm, it recommendations that you install nvm globally using the -g switch.

npm install -g nvm

Also there is a . in the path variable that they recommend.

export PATH=./node_modules/.bin:$PATH

so maybe your path should be

C:\Program Files (x86)\nodejs\node_modules\npm\\.bin

Copy entire directory contents to another directory?

This is my piece of Groovy code for that. Tested.

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}

How to remove ASP.Net MVC Default HTTP Headers?

X-Powered-By is a custom header in IIS. Since IIS 7, you can remove it by adding the following to your web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

This header can also be modified to your needs, for more information refer to http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders


Add this to web.config to get rid of the X-AspNet-Version header:

<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

Finally, to remove X-AspNetMvc-Version, edit Global.asax.cs and add the following in the Application_Start event:

protected void Application_Start()
{
    MvcHandler.DisableMvcResponseHeader = true;
}

You can also modify headers at runtime via the Application_PreSendRequestHeaders event in Global.asax.cs. This is useful if your header values are dynamic:

protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}

HTTP POST using JSON in Java

You can use the following code with Apache HTTP:

String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

response = client.execute(request);

Additionally you can create a json object and put in fields into the object like this

HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));

Refresh certain row of UITableView based on Int in Swift

For a soft impact animation solution:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
tableView.reloadRows(at: [indexPath], with: .fade)

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

This is another way to protect the app from crashing:

Swift 3:

let indexPath = IndexPath(item: row, section: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.index(of: indexPath as IndexPath) {
    if visibleIndexPaths != NSNotFound {
        tableView.reloadRows(at: [indexPath], with: .fade)
    }
}

Swift 2.x:

let indexPath = NSIndexPath(forRow: row, inSection: 0)
if let visibleIndexPaths = tableView.indexPathsForVisibleRows?.indexOf(indexPath) {
   if visibleIndexPaths != NSNotFound {
      tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
   }
}

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

Is there a way to have printf() properly print out an array (of floats, say)?

I don't think there is a way to print array for you in printf. "printf" function has no idea how long your array is.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

The "ojdbc.jar" is not in the CLASSPATH of your application server.

Just tell us which application server it is and we will tell you where the driver should be placed.

Edit: I saw the tag so it has to be placed in folder "$JBOSS_HOME/server/default/lib/"

Angularjs error Unknown provider

bmleite has the correct answer about including the module.

If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.

Remember:

angular.module('ModuleName', [])   // creates a module.

angular.module('ModuleName')       // gets you a pre-existing module.

So if you are extending a existing module, remember not to overwrite when trying to fetch it.

How do I pass a datetime value as a URI parameter in asp.net mvc?

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

I would suggest sending the date value as a parameter rather than as part of the route:

 mysite/Controller/Action?date=21-9-2009 10:20

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

 encodeURIComponent(yourstring)

It is a method within Javascript.

On the Server Side:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

Passing variable number of arguments around

Short answer

/// logs all messages below this level, level 0 turns off LOG 
#ifndef LOG_LEVEL
#define LOG_LEVEL 5  // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose
#endif
#define _LOG_FORMAT_SHORT(letter, format) "[" #letter "]: " format "\n"

/// short log
#define log_s(level, format, ...)     \                                                                                  
    if (level <= LOG_LEVEL)            \                                                                                     
    printf(_LOG_FORMAT_SHORT(level, format), ##__VA_ARGS__)

usage

log_s(1, "fatal error occurred");
log_s(3, "x=%d and name=%s",2, "ali");

output

[1]: fatal error occurred
[3]: x=2 and name=ali

log with file and line number

const char* _getFileName(const char* path)
{
    size_t i = 0;
    size_t pos = 0;
    char* p = (char*)path;
    while (*p) {
        i++;
        if (*p == '/' || *p == '\\') {
            pos = i;
        }
        p++;
    }
    return path + pos;
}

#define _LOG_FORMAT(letter, format)      \                                                                        
    "[" #letter "][%s:%u] %s(): " format "\n", _getFileName(__FILE__), __LINE__, __FUNCTION__

#ifndef LOG_LEVEL
#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose
#endif

/// long log
#define log_l(level, format, ...)     \                                                                               
    if (level <= LOG_LEVEL)            \                                                                                         
    printf(_LOG_FORMAT(level, format), ##__VA_ARGS__)

usage

log_s(1, "fatal error occurred");
log_s(3, "x=%d and name=%s",2, "ali");

output

[1][test.cpp:97] main(): fatal error occurred
[3][test.cpp:98] main(): x=2 and name=ali

custom print function

you can write custom print function and pass ... args to it and it is also possible to combine this with methods above. source from here

int print_custom(const char* format, ...)
{
    static char loc_buf[64];
    char* temp = loc_buf;
    int len;
    va_list arg;
    va_list copy;
    va_start(arg, format);
    va_copy(copy, arg);
    len = vsnprintf(NULL, 0, format, arg);
    va_end(copy);
    if (len >= sizeof(loc_buf)) {
        temp = (char*)malloc(len + 1);
        if (temp == NULL) {
            return 0;
        }
    }
    vsnprintf(temp, len + 1, format, arg);
    printf(temp); // replace with any print function you want
    va_end(arg);
    if (len >= sizeof(loc_buf)) {
        free(temp);
    }
    return len;
}

What is the largest TCP/IP network port number allowable for IPv4?

Just a followup to smashery's answer. The ephemeral port range (on Linux at least, and I suspect other Unices as well) is not a fixed. This can be controlled by writing to /proc/sys/net/ipv4/ip_local_port_range

The only restriction (as far as IANA is concerned) is that ports below 1024 are designated to be well-known ports. Ports above that are free for use. Often you'll find that ports below 1024 are restricted to superuser access, I believe for this very reason.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.