Programs & Examples On #Template mixins

How to store image in SQL Server database tables column

Insert Into FEMALE(ID, Image)
Select '1', BulkColumn 
from Openrowset (Bulk 'D:\thepathofimage.jpg', Single_Blob) as Image

You will also need admin rights to run the query.

Cannot open local file - Chrome: Not allowed to load local resource

If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.

If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).

See also:

Threading pool similar to the multiprocessing Pool?

another way can be adding the process to thethread queue pool

import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=cpus) as executor:
    for i in range(10):
        a = executor.submit(arg1, arg2,....)

How to append to a file in Node?

Use a+ flag to append and create a file (if doesn't exist):

fs.writeFile('log.txt', 'Hello Node', { flag: "a+" }, (err) => {
  if (err) throw err;
  console.log('The file is created if not existing!!');
}); 

Docs: https://nodejs.org/api/fs.html#fs_file_system_flags

How can I catch all the exceptions that will be thrown through reading and writing a file?

While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

try{
    // IO code
} catch (Exception e){
    if(e instanceof IOException){
        // handle this exception type
    } else if (e instanceof AnotherExceptionType){
        //handle this one
    } else {
        // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
        throw e;
    }
}

However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

try{
    // IO code
} catch (Throwable t){
    if(t instanceof Exception){
        if(t instanceof IOException){
            // handle this exception type
        } else if (t instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else if (t instanceof Error){
        if(t instanceof IOError){
            // handle this Error
        } else if (t instanceof AnotherError){
            //handle different Error
        } else {
            // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else {
        // This should never be reached, unless you have subclassed Throwable for your own purposes.
        throw t;
    }
}

Using curl POST with variables defined in bash script functions

You don't need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the data argument should be quoted.

First, write a function that generates the post data of your script. This saves you from all sort of headaches concerning shell quoting and makes it easier to read an maintain the script than feeding the post data on curl's invocation line as in your attempt:

generate_post_data()
{
  cat <<EOF
{
  "account": {
    "email": "$email",
    "screenName": "$screenName",
    "type": "$theType",
    "passwordSettings": {
      "password": "$password",
      "passwordConfirm": "$password"
    }
  },
  "firstName": "$firstName",
  "lastName": "$lastName",
  "middleName": "$middleName",
  "locale": "$locale",
  "registrationSiteId": "$registrationSiteId",
  "receiveEmail": "$receiveEmail",
  "dateOfBirth": "$dob",
  "mobileNumber": "$mobileNumber",
  "gender": "$gender",
  "fuelActivationDate": "$fuelActivationDate",
  "postalCode": "$postalCode",
  "country": "$country",
  "city": "$city",
  "state": "$state",
  "bio": "$bio",
  "jpFirstNameKana": "$jpFirstNameKana",
  "jpLastNameKana": "$jpLastNameKana",
  "height": "$height",
  "weight": "$weight",
  "distanceUnit": "MILES",
  "weightUnit": "POUNDS",
  "heightUnit": "FT/INCHES"
}
EOF
}

It is then easy to use that function in the invocation of curl:

curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$(generate_post_data)" "https://xxx:[email protected]/xxxxx/xxxx/xxxx"

This said, here are a few clarifications about shell quoting rules:

The double quotes in the -H arguments (as in -H "foo bar") tell bash to keep what's inside as a single argument (even if it contains spaces).

The single quotes in the --data argument (as in --data 'foo bar') do the same, except they pass all text verbatim (including double quote characters and the dollar sign).

To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: 'foo bar'"$variable"'more foo'.

How can I give access to a private GitHub repository?

Your team members must be accessing the repository using SSH & for that they have to have their ssh key mapped with github account. This will work if they map their ssh key with github account and also the repository has public rights, which they want to access.

How to prevent Google Colab from disconnecting?

The above answers with the help of some scripts maybe work well. I have a solution(or a kind of trick) for that annoying disconnection without scripts, especially when your program must read data from your google drive, like training a deep learning network model, where using scripts to do reconnect operation is of no use because once you disconnect with your colab, the program is just dead, you should manually connect to your google drive again to make your model able to read dataset again, but the scripts will not do that thing.
I've already test it many times and it works well.
When you run a program on the colab page with a browser(I use Chrome), just remember that don't do any operation to your browser once your program starts running, like: switch to other webpages, open or close another webpage, and so on, just just leave it alone there and waiting for your program finish running, you can switch to another software, like pycharm to keep writing your codes but not switch to another webpage. I don't know why open or close or switch to other pages will cause the connection problem of the google colab page, but each time I try to bothered my browser, like do some search job, my connection to colab will soon break down.

How to extract an assembly from the GAC?

From a Powershell script, you can try this. I only had a single version of the assembly in the GAC so this worked just fine.

cd "c:\Windows\Microsoft.NET\assembly\GAC_MSIL\"
Get-ChildItem assemblypath -Recurse -Include *.dll |  Copy-Item -Destination "c:\folder to copy to"

where the assembly path can use wildcards.

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

Python - converting a string of numbers into a list of int

You can also use list comprehension on splitted string

[ int(x) for x in example_string.split(',') ]

How to use a table type in a SELECT FROM statement?

In SQL you may only use table type which is defined at schema level (not at package or procedure level), and index-by table (associative array) cannot be defined at schema level. So - you have to define nested table like this

create type exch_row as object (
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);

create type exch_tbl as table of exch_row;

And then you can use it in SQL with TABLE operator, for example:

declare
   l_row     exch_row;
   exch_rt   exch_tbl;
begin
   l_row := exch_row('PLN', 100, 100);
   exch_rt  := exch_tbl(l_row);

   for r in (select i.*
               from item i, TABLE(exch_rt) rt
              where i.currency = rt.currency_cd) loop
      -- your code here
   end loop;
end;
/

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

Example of Mockito's argumentCaptor

The two main differences are:

  • when you capture even a single argument, you are able to make much more elaborate tests on this argument, and with more obvious code;
  • an ArgumentCaptor can capture more than once.

To illustrate the latter, say you have:

final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);

verify(x, times(4)).someMethod(captor.capture()); // for instance

Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.

This or any number of arguments in fact, since a VerificationMode is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.

This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatchers -- particularly if you combine mockito with assertj.

Oh, and please consider using TestNG instead of JUnit.

How to autosize and right-align GridViewColumn data in WPF?

To make each of the columns autosize you can set Width="Auto" on the GridViewColumn.

To right-align the text in the ID column you can create a cell template using a TextBlock and set the TextAlignment. Then set the ListViewItem.HorizontalContentAlignment (using a style with a setter on the ListViewItem) to make the cell template fill the entire GridViewCell.

Maybe there is a simpler solution, but this should work.

Note: the solution requires both HorizontalContentAlignment=Stretch in Window.Resources and TextAlignment=Right in the CellTemplate.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</Window.Resources>
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Id}" TextAlignment="Right" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

Get user profile picture by Id

You can use the following endpoint to get the image.jfif instead of jpg:

https://graph.facebook.com/v3.2/{user-id}/picture

Note that you won't be able to see the image, only download it.

How to perform element-wise multiplication of two lists?

Yet another answer:

-1 ... requires import
+1 ... is very readable

import operator
a = [1,2,3,4]
b = [10,11,12,13]

list(map(operator.mul, a, b))

outputs [10, 22, 36, 52]

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

Executing Batch File in C#

This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:

static void ExecuteCommand(string command)
{
    int exitCode;
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    // *** Redirect the output ***
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);
    process.WaitForExit();

    // *** Read the streams ***
    // Warning: This approach can lead to deadlocks, see Edit #2
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    exitCode = process.ExitCode;

    Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
    process.Close();
}

static void Main()
{
    ExecuteCommand("echo testing");
}   

* EDIT *

Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).

This does work if the batch file is not located in C:\Windows\System32. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.

* EDIT 2 * It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before WaitForExit or by reading both stderr and stdout synchronously one after the other.

This should not happen if using the asynchronous read methods instead, as in the following example:

static void ExecuteCommand(string command)
{
    var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    var process = Process.Start(processInfo);

    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("output>>" + e.Data);
    process.BeginOutputReadLine();

    process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("error>>" + e.Data);
    process.BeginErrorReadLine();

    process.WaitForExit();

    Console.WriteLine("ExitCode: {0}", process.ExitCode);
    process.Close();
}

JavaScriptSerializer.Deserialize - how to change field names

By creating a custom JavaScriptConverter you can map any name to any property. But it does require hand coding the map, which is less than ideal.

public class DataObjectJavaScriptConverter : JavaScriptConverter
{
    private static readonly Type[] _supportedTypes = new[]
    {
        typeof( DataObject )
    };

    public override IEnumerable<Type> SupportedTypes 
    { 
        get { return _supportedTypes; } 
    }

    public override object Deserialize( IDictionary<string, object> dictionary, 
                                        Type type, 
                                        JavaScriptSerializer serializer )
    {
        if( type == typeof( DataObject ) )
        {
            var obj = new DataObject();
            if( dictionary.ContainsKey( "user_id" ) )
                obj.UserId = serializer.ConvertToType<int>( 
                                           dictionary["user_id"] );
            if( dictionary.ContainsKey( "detail_level" ) )
                obj.DetailLevel = serializer.ConvertToType<DetailLevel>(
                                           dictionary["detail_level"] );

            return obj;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize( 
            object obj, 
            JavaScriptSerializer serializer )
    {
        var dataObj = obj as DataObject;
        if( dataObj != null )
        {
            return new Dictionary<string,object>
            {
                {"user_id", dataObj.UserId },
                {"detail_level", dataObj.DetailLevel }
            }
        }
        return new Dictionary<string, object>();
    }
}

Then you can deserialize like so:

var serializer = new JavaScriptSerializer();
serialzer.RegisterConverters( new[]{ new DataObjectJavaScriptConverter() } );
var dataObj = serializer.Deserialize<DataObject>( json );

What is the difference between utf8mb4 and utf8 charsets in MySQL?

  • utf8 is MySQL's older, flawed implementation of UTF-8 which is in the process of being deprecated.
  • utf8mb4 is what they named their fixed UTF-8 implementation, and is what you should use right now.

In their flawed version, only characters in the first 64k character plane - the basic multilingual plane - work, with other characters considered invalid. The code point values within that plane - 0 to 65535 (some of which are reserved for special reasons) can be represented by multi-byte encodings in UTF-8 of up to 3 bytes, and MySQL's early version of UTF-8 arbitrarily decided to set that as a limit. At no point was this limitation a correct interpretation of the UTF-8 rules, because at no point was UTF-8 defined as only allowing up to 3 bytes per character. In fact, the earliest definitions of UTF-8 defined it as having up to 6 bytes (since revised to 4). MySQL's original version was always arbitrarily crippled.

Back when MySQL released this, the consequences of this limitation weren't too bad as most Unicode characters were in that first plane. Since then, more and more newly defined character ranges have been added to Unicode with values outside that first plane. Unicode itself defines 17 planes, though so far only 7 of these are used.

In an effort not to break old code making any particular assumptions, MySQL retained the broken implementation and called the newer, fixed version utf8mb4. This has led to some confusion with the name being misinterpreted as if it's some kind of extension to UTF-8 or alternative form of UTF-8, rather than MySQL's implementation of the true UTF-8.

Future versions of MySQL will eventually phase out the older version, and for now it can be considered deprecated. For the foreseeable future you need to use utf8mb4 to ensure correct UTF-8 encoding. After sufficient time has passed, the current utf8 will be removed, and at some future date utf8 will rise again, this time referring to the fixed version, though utf8mb4 will continue to unambiguously refer to the fixed version.

jQuery & CSS - Remove/Add display:none

Considering lolesque's comment to best answer you can add either an attribute or a class to show/hide elements with display properties that differs from what it normally has, if your site needs backwards compatibility I would suggest making a class and adding/removing it to show/display the element

.news-show {
display:inline-block;
}

.news-hide {
display:none;
}

Replace inline-block with your preferred display method of your choice and use jquerys addclass https://api.jquery.com/addclass/ and removeclass https://api.jquery.com/removeclass/ instead of show/hide, if backwards compatibility is no problem you can use attributes like this.

.news[data-news-visible=show] {
display:inline-block;
}

.news[data-news-visible=hide] {
display:none;
}

And use jquerys attr() http://api.jquery.com/attr/ to show and hide the element.

Whichever method you prefer it makes you able to easily implement css3 animations when showing/hiding elements this way

node and Error: EMFILE, too many open files

Using the graceful-fs module by Isaac Schlueter (node.js maintainer) is probably the most appropriate solution. It does incremental back-off if EMFILE is encountered. It can be used as a drop-in replacement for the built-in fs module.

How to find char in string and get all the indexes?

As the rule of thumb, NumPy arrays often outperform other solutions while working with POD, Plain Old Data. A string is an example of POD and a character too. To find all the indices of only one char in a string, NumPy ndarrays may be the fastest way:

def find1(str, ch):
  # 0.100 seconds for 1MB str 
  npbuf = np.frombuffer(str, dtype=np.uint8) # Reinterpret str as a char buffer
  return np.where(npbuf == ord(ch))          # Find indices with numpy

def find2(str, ch):
  # 0.920 seconds for 1MB str 
  return [i for i, c in enumerate(str) if c == ch] # Find indices with python

Table Height 100% inside Div element

Not possible without assigning height value to div.

Add this

body, html{height:100%}
div{height:100%}
table{background:green; width:450px}    ?

DEMO

How to install the current version of Go in Ubuntu Precise

These days according to the golang github with for Ubuntu, it's possible to install the latest version of Go easily via a snap:

Using snaps also works quite well:

# This will give you the latest version of go
$ sudo snap install --classic go

Potentially preferable to fussing with outdated and/or 3rd party PPAs

Loading scripts after page load?

Here is a code I am using and which is working for me.

window.onload = function(){
    setTimeout(function(){
        var scriptElement=document.createElement('script');
        scriptElement.type = 'text/javascript';
        scriptElement.src = "vendor/js/jquery.min.js";
        document.head.appendChild(scriptElement);

        setTimeout(function() {
            var scriptElement1=document.createElement('script');
            scriptElement1.type = 'text/javascript';
            scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
            document.head.appendChild(scriptElement1);
        }, 100);
        setTimeout(function() {
            $(document).ready(function(e){
                lc_lightbox('.elem', {
                    wrap_class: 'lcl_fade_oc',
                    gallery : true, 
                    thumb_attr: 'data-lcl-thumb', 
                    slideshow_time  : 3000,
                    skin: 'minimal',
                    radius: 0,
                    padding : 0,
                    border_w: 0,
                }); 
            });
        }, 200);

    }, 150);
};

How do I change the hover over color for a hover over table in Bootstrap?

This worked for me:

.table tbody tr:hover td, .table tbody tr:hover th {
    background-color: #eeeeea;
}

Ruby, remove last N characters from a string?

irb> 'now is the time'[0...-4]
=> "now is the "

Adjusting the Xcode iPhone simulator scale and size

You can set any scale you wish. It`s became actual after 6+ simulator been presented

To obtain it follow next easy steps:

  1. quit simulator if open
  2. open terminal (from spotlight for example)
  3. paste next text to terminal and press enter

defaults write ~/Library/Preferences/com.apple.iphonesimulator SimulatorWindowLastScale "0.4"

You can try any scales changing 0.4 to desired value.

To reset this custom scale, just apply any standard scale from simulator menu in way described above.

How to install packages offline?

The pip download command lets you download packages without installing them:

pip download -r requirements.txt

(In previous versions of pip, this was spelled pip install --download -r requirements.txt.)

Then you can use pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt to install those downloaded sdists, without accessing the network.

How do I run two commands in one line in Windows CMD?

Like this on all Microsoft OSes since 2000, and still good today:

dir & echo foo

If you want the second command to execute only if the first exited successfully:

dir && echo foo

The single ampersand (&) syntax to execute multiple commands on one line goes back to Windows XP, Windows 2000, and some earlier NT versions. (4.0 at least, according to one commenter here.)

There are quite a few other points about this that you'll find scrolling down this page.

Historical data follows, for those who may find it educational.

Prior to that, the && syntax was only a feature of the shell replacement 4DOS before that feature was added to the Microsoft command interpreter.

In Windows 95, 98 and ME, you'd use the pipe character instead:

dir | echo foo

In MS-DOS 5.0 and later, through some earlier Windows and NT versions of the command interpreter, the (undocumented) command separator was character 20 (Ctrl+T) which I'll represent with ^T here.

dir ^T echo foo

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

jQuery UI autocomplete with JSON

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

PHP Pass variable to next page

HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. Except if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure.

Session:

//On page 1
$_SESSION['varname'] = $var_value;

//On page 2
$var_value = $_SESSION['varname'];

Remember to run the session_start(); statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.

Cookie:

//One page 1
$_COOKIE['varname'] = $var_value;

//On page 2
$var_value = $_COOKIE['varname'];

The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id.

GET and POST

You can add the variable in the link to the next page:

<a href="page2.php?varname=<?php echo $var_value ?>">Page2</a>

This will create a GET variable.

Another way is to include a hidden field in a form that submits to page two:

<form method="get" action="page2.php">
    <input type="hidden" name="varname" value="var_value">
    <input type="submit">
</form>

And then on page two:

//Using GET
$var_value = $_GET['varname'];

//Using POST
$var_value = $_POST['varname'];

//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];

Just change the method for the form to post if you want to do it via post. Both are equally insecure, although GET is easier to hack.

The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

a:hover, /* OPTIONAL*/
a:visited,
a:focus
{text-decoration: none !important;}

How to decode a Base64 string?

Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.

Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.

While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.

I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.

Base64decode("the answer to life the universe and everything") = 00101010

Checking if an object is a number in C#

Assuming your input is a string...

There are 2 ways:

use Double.TryParse()

double temp;
bool isNumber = Double.TryParse(input, out temp);

use Regex

 bool isNumber = Regex.IsMatch(input,@"-?\d+(\.\d+)?");

How to get the containing form of an input?

I needed to use element.attr('form') instead of element.form.

I use Firefox on Fedora 12.

Renaming Columns in an SQL SELECT Statement

you have to rename each column

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

Iterate over the lines of a string

You can iterate over "a file", which produces lines, including the trailing newline character. To make a "virtual file" out of a string, you can use StringIO:

import io  # for Py2.7 that would be import cStringIO as io

for line in io.StringIO(foo):
    print(repr(line))

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

The PropertiesPlaceholderConfigurer bean has an alternative property called "propertiesArray". Use this instead of the "properties" property, and configure it with an <array> of property references.

How I add Headers to http.get or http.post in Typescript and angular 2?

Be sure to declare HttpHeaders without null values.

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))

Otherwise, if you try to add a null value to HttpHeaders it will give you an error.

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

How do I pipe or redirect the output of curl -v?

Your URL probably has ampersands in it. I had this problem, too, and I realized that my URL was full of ampersands (from CGI variables being passed) and so everything was getting sent to background in a weird way and thus not redirecting properly. If you put quotes around the URL it will fix it.

Replacing from match to end-of-line

Use this, two<anything any number of times><end of line>

's/two.*$/BLAH/g'

Multi-key dictionary in c#?

I've also used tuples as jason in his answer does. However, I suggest you simply define a tuple as a struct:

public struct Tuple<T1, T2> {
    public readonly T1 Item1;
    public readonly T2 Item2;
    public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2;} 
}

public static class Tuple { // for type-inference goodness.
    public static Tuple<T1,T2> Create<T1,T2>(T1 item1, T2 item2) { 
        return new Tuple<T1,T2>(item1, item2); 
    }
}

You get immutability, .GetHashcode and .Equals for free, which (while you're waiting for C# 4.0) is nice 'n simple...

One warning however: the default GetHashcode implementation (sometimes) only considers the first field so make sure to make the first field the most discriminating or implement GetHashcode yourself (e.g. using FieldwiseHasher.Hash(this) from ValueUtils), otherwise you'll likely run into scalability issues.

Also, you get to avoid nulls which tend to complicate matters (and if you really want nulls, you just make your Tuple<> nullable). Slightly offtopic, am I the only one annoyed at the framework-level lack of support for non-null references? I work on large project, and occasionally a null creeps in somewhere it really shouldn't -- and hey presto, you get a nullreference exception -- but with a stack trace that points you to the reference's first usage, not the actually faulty code.

Of course, .NET 4.0 is pretty old by now; most of us can just use .NET 4.0's tuple.

Edit: to workaround the poor GetHashCode implementation that .NET provides for structs I've written ValueUtils, which also allows you to use real names for your multi-field keys; that means you might write something like:

sealed class MyValueObject : ValueObject<MyValueObject> {
    public DayOfWeek day;
    public string NamedPart;
    //properties work fine too
}

...which hopefully makes it easier to have human-readable names for data with value semantics, at least until some future version of C# implements proper tuples with named members; hopefully with decent hashcodes ;-).

Create a zip file and download it

but the file i am getting from server after download it gives the size of 226 bytes

This is the size of a ZIP header. Apparently there is no data in the downloaded ZIP file. So, can you verify that the files to be added into the ZIP file are, indeed, there (relative to the path of the download PHP script)?

Consider adding a check on addFile too:

foreach($file_names as $file)
{
    $inputFile = $file_path . $file;
    if (!file_exists($inputFile))
        trigger_error("The input file $inputFile does not exist", E_USER_ERROR);
    if (!is_readable($inputFile))
        trigger_error("The input file $inputFile exists, but has wrong permissions or ownership", E_USER_ERROR);
    if (!$zip->addFile($inputFile, $file))
        trigger_error("Could not add $inputFile to ZIP file", E_USER_ERROR);
}

The observed behaviour is consistent with some problem (path error, permission problems, ...) preventing the files from being added to the ZIP file. On receiving an "empty" ZIP file, the client issues an error referring to the ZIP central directory missing (the actual error being that there is no directory, and no files).

How to insert default values in SQL table?

Best practice it to list your columns so you're independent of table changes (new column or column order etc)

insert into table1 (field1, field3)  values (5,10)

However, if you don't want to do this, use the DEFAULT keyword

insert into table1 values (5, DEFAULT, 10, DEFAULT)

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

Constructor overloading in Java - best practice

While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.

public class Simple {

    public Simple() {
        this(null);
    }

    public Simple(Resource r) {
        this(r, null);
    }

    public Simple(Resource r1, Resource r2) {
        // Guard statements, initialize resources or throw exceptions if
        // the resources are wrong
        if (r1 == null) {
            r1 = new Resource();
        }
        if (r2 == null) {
            r2 = new Resource();
        }

        // do whatever with resources
    }

}

From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:

Make a parameter class

public class SimpleParams {
    Resource r1;
    Resource r2;
    // Imagine there are setters and getters here but I'm too lazy 
    // to write it out. you can make it the parameter class 
    // "immutable" if you don't have setters and only set the 
    // resources through the SimpleParams constructor
}

The constructor in Simple only either needs to split the SimpleParams parameter:

public Simple(SimpleParams params) {
    this(params.getR1(), params.getR2());
}

…or make SimpleParams an attribute:

public Simple(Resource r1, Resource r2) {
    this(new SimpleParams(r1, r2));
}

public Simple(SimpleParams params) {
    this.params = params;
}

Make a factory class

Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:

public interface ResourceFactory {
    public Resource createR1();
    public Resource createR2();
}

The constructor is then done in the same manner as with the parameter class:

public Simple(ResourceFactory factory) {
    this(factory.createR1(), factory.createR2());
} 

Make a combination of both

Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple class that they're used the same way.

Windows shell command to get the full path to the current directory?

For Windows, cd by itself will show you the current working directory.

For UNIX and workalike systems, pwd will perform the same task. You can also use the $PWD shell variable under some shells. I am not sure if Windows supports getting the current working directory via a shell variable or not.

HTML/CSS--Creating a banner/header

Remove the z-index value.

I would also recommend this approach.

HTML:

<header class="main-header" role="banner">
  <img src="mybannerimage.gif" alt="Banner Image"/>
</header>

CSS:

.main-header {
  text-align: center;
}

This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.

Create table (structure) from existing table

Copy the table structure:-
select * into newtable from oldtable where 1=2;

Copy the table structure along with table data:-
select * into newtable from oldtable where 1=1;

Send email using java

You can find a complete and very simple java class for sending emails using Google(gmail) account here,

Send email using java and Google account

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

Div Scrollbar - Any way to style it?

Looking at the web I find some simple way to style scrollbars.

This is THE guy! http://almaer.com/blog/creating-custom-scrollbars-with-css-how-css-isnt-great-for-every-task

And here my implementation! https://dl.dropbox.com/u/1471066/cloudBI/cssScrollbars.png

/* Turn on a 13x13 scrollbar */
::-webkit-scrollbar {
    width: 10px;
    height: 13px;
}

::-webkit-scrollbar-button:vertical {
    background-color: silver;
    border: 1px solid gray;
}

/* Turn on single button up on top, and down on bottom */
::-webkit-scrollbar-button:start:decrement,
::-webkit-scrollbar-button:end:increment {
    display: block;
}

/* Turn off the down area up on top, and up area on bottom */
::-webkit-scrollbar-button:vertical:start:increment,
::-webkit-scrollbar-button:vertical:end:decrement {
    display: none;
}

/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:vertical:increment {
    display: none;
}

/* Place The scroll up button at the up */
::-webkit-scrollbar-button:vertical:decrement {
    display: none;
}

/* Place The scroll down button at the bottom */
::-webkit-scrollbar-button:horizontal:increment {
    display: none;
}

/* Place The scroll up button at the up */
::-webkit-scrollbar-button:horizontal:decrement {
    display: none;
}

::-webkit-scrollbar-track:vertical {
    background-color: blue;
    border: 1px dashed pink;
}

/* Top area above thumb and below up button */
::-webkit-scrollbar-track-piece:vertical:start {
    border: 0px;
}

/* Bottom area below thumb and down button */
::-webkit-scrollbar-track-piece:vertical:end {
    border: 0px;
}

/* Track below and above */
::-webkit-scrollbar-track-piece {
    background-color: silver;
}

/* The thumb itself */
::-webkit-scrollbar-thumb:vertical {
    height: 50px;
    background-color: gray;
}

/* The thumb itself */
::-webkit-scrollbar-thumb:horizontal {
    height: 50px;
    background-color: gray;
}

/* Corner */
::-webkit-scrollbar-corner:vertical {
    background-color: black;
}

/* Resizer */
::-webkit-scrollbar-resizer:vertical {
    background-color: gray;
}

How to check View Source in Mobile Browsers (Both Android && Feature Phone)

The view-source url prefix trick didn't work for me using chrome on an iphone. There are apps I could have installed to do this I guess but for whatever reason I just preferred to do it myself rather than install 'yet another app'.

I found this nice quick tutorial for how to setup a bookmark on mobile safari that will automatically open the view source of a page: https://appletoolbox.com/2014/03/how-to-view-webpage-html-source-codes-on-ipad-iphone-no-app-required/

It worked flawlessly for me and now I have it set as a permanent bookmark any time I want, with no app installed.

Edit: There are basically 6 steps which should work for either Chrome or Safari. Instructions for Safari are:

  1. Open Safari and browse to an arbitrary page.
  2. Select the "Share" (or action") button in Safari (looks like a square with an arrow coming out of the top).
  3. Select "Add Bookmark"
  4. Delete the page title and replace it with something useful like "Show Page Source". Click Save.
  5. Next browse to this exact Stack Overflow answer on your phone and copy the javascript code below to your phone clipboard (code credit: Rob Flaherty):
javascript:(function(){var a=window.open('about:blank').document;a.write('<!DOCTYPE html><html><head><title>Source of '+location.href+'</title><meta name="viewport" content="width=device-width" /></head><body></body></html>');a.close();var b=a.body.appendChild(a.createElement('pre'));b.style.overflow='auto';b.style.whiteSpace='pre-wrap';b.appendChild(a.createTextNode(document.documentElement.innerHTML))})();
  1. Open the "Bookmarks" in Safari and opt to Edit the newly created Show Page Source bookmark. Delete whatever was previously saved in the Address field and instead paste in the Javascript code. Save it.
  2. (Optional) Profit!

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

For me, removing WebDAV from my server caused the application to return a 503 Service Unavailable Error message when using PUT or DELETE, so I re-installed it back again. I also tried completely removing .NET Framework 4.5 and reinstalling it and also tried re-registering as suggested but to no avail.

I was able to fix this by disabling WebDAV for the individual application pool, this stopped the 'bad module' error when using PUT or DELETE.

Disable WebDAV for Individual App Pool:

  1. Click the affected application pool
  2. Find WebDAV Authoring Tools in the list
  3. Click to open it
  4. Click Disable WebDAV in the top right.

Ta daaaa!

I still left the remove items in my web.config file.

 <system.webServer>
    <modules>
      <remove name="WebDAVModule"/>
    </modules>
    <handlers>
      <remove name="WebDAV" />
    </handlers>
 <system.webServer>

This link is where I found the instructions but it's not very clear.

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

NuGet auto package restore does not work with MSBuild

Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.

The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.

To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution

<Target Name="BeforeBuild">
  <Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>

For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

jQuery show/hide not working

Just add the document ready function, this way it waits until the DOM has been loaded, also by using the :visible pseudo you can write a simple show and hide function.

Sample

 $(document).ready(function(){

    $( '.expand' ).click(function() {
         if($( '.img_display_content' ).is(":visible")){
              $( '.img_display_content' ).hide();
         } else{
              $( '.img_display_content' ).show();
         }

    });
});

Java 6 Unsupported major.minor version 51.0

That version number (51.0) indicates that you are trying to run classes compiled for Java 7. You will need to recompile them for Java 6.

Note, however, that some features may no longer be compatible with Java 6, which is very old, and no longer (publicly) supported by Oracle.

Android: how to convert whole ImageView to Bitmap?

Have you tried:

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

java.time

The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

Parse as a ZonedDateTime.

String input = "Mon Jun 18 00:00:00 IST 2012";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM dd HH:mm:ss z uuuu" )
                                       .withLocale( Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

Extract a date-only object, a LocalDate, without any time-of-day and without any time zone.

LocalDate ld = zdt.toLocalDate();
DateTimeFormatter fLocalDate = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( fLocalDate) ;

Dump to console.

System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ld: " + ld );
System.out.println( "output: " + output );

input: Mon Jun 18 00:00:00 IST 2012

zdt: 2012-06-18T00:00+03:00[Asia/Jerusalem]

ld: 2012-06-18

output: 18/06/2012

See this code run live in IdeOne.com.

Poor choice of format

Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.

Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For example, your use of IST may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.


About java.time

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

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

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

Where to obtain the java.time classes?

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

How can I use grep to find a word inside a folder?

Similar to the answer posted by @eLRuLL, a easier way to specify a search that respects word boundaries is to use the -w option:

grep -wnr "yourString" .

CSS3 Rotate Animation

To achieve the 360 degree rotation, here is the Working Solution.

The HTML:

<img class="image" src="your-image.png">

The CSS:

.image {
    overflow: hidden;
    transition-duration: 0.8s;
    transition-property: transform;
}
.image:hover {
    transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
}

You have to hover on the image and you will get the 360 degree rotation effect.

PS: Add a -webkit- extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE

Python "SyntaxError: Non-ASCII character '\xe2' in file"

Change the file character encoding,

put below line to top of your code always

# -*- coding: utf-8 -*-

PHP split alternative?

  • preg_split if you need to split by regular expressions.
  • str_split if you need to split by characters.
  • explode if you need to split by something simple.

Also for the future, if you ever want to know what PHP wants you to use if something is deprecated you can always check out the function in the manual and it will tell you alternatives.

Copy directory contents into a directory with python

I found this code working:

from distutils.dir_util import copy_tree

# copy subdirectory example
fromDirectory = "/a/b/c"
toDirectory = "/x/y/z"

copy_tree(fromDirectory, toDirectory)

Reference:

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Just made this in a few minutes:

using System;
using System.Management;

namespace WindowsFormsApplication_CS
{
  class NetworkManagement
  {
    public void setIP(string ip_address, string subnet_mask)
    {
      ManagementClass objMC =
        new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setIP;
          ManagementBaseObject newIP =
            objMO.GetMethodParameters("EnableStatic");

          newIP["IPAddress"] = new string[] { ip_address };
          newIP["SubnetMask"] = new string[] { subnet_mask };

          setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
        }
      }
    }

    public void setGateway(string gateway)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setGateway;
          ManagementBaseObject newGateway =
            objMO.GetMethodParameters("SetGateways");

          newGateway["DefaultIPGateway"] = new string[] { gateway };
          newGateway["GatewayCostMetric"] = new int[] { 1 };

          setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
        }
      }
    }

    public void setDNS(string NIC, string DNS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          // if you are using the System.Net.NetworkInformation.NetworkInterface
          // you'll need to change this line to
          // if (objMO["Caption"].ToString().Contains(NIC))
          // and pass in the Description property instead of the name 
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject newDNS =
              objMO.GetMethodParameters("SetDNSServerSearchOrder");
            newDNS["DNSServerSearchOrder"] = DNS.Split(',');
            ManagementBaseObject setDNS =
              objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
          }
        }
      }
    }

    public void setWINS(string NIC, string priWINS, string secWINS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject setWINS;
            ManagementBaseObject wins =
            objMO.GetMethodParameters("SetWINSServer");
            wins.SetPropertyValue("WINSPrimaryServer", priWINS);
            wins.SetPropertyValue("WINSSecondaryServer", secWINS);

            setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
          }
        }
      }
    } 
  }
}

Excel data validation with suggestions/autocomplete

This is a solution how to make autocomplete drop down list with VBA :


Firstly you need to insert a combo box into the worksheet and change its properties, and then running the VBA code to enable the autocomplete.

  1. Get into the worksheet which contains the drop down list you want it to be autocompleted.

  2. Before inserting the Combo box, you need to enable the Developer tab in the ribbon.

a). In Excel 2010 and 2013, click File > Options. And in the Options dialog box, click Customize Ribbon in the right pane, check the Developer box, then click the OK button.

b). In Outlook 2007, click Office button > Excel Options. In the Excel Options dialog box, click Popular in the right bar, then check the Show Developer tabin the Ribbon box, and finally click the OK button.

  1. Then click Developer > Insert > Combo Box under ActiveX Controls.

  2. Draw the combo box in current opened worksheet and right click it. Select Properties in the right-clicking menu.

  3. Turn off the Design Mode with clicking Developer > Design Mode.

  4. Right click on the current opened worksheet tab and click View Code.

  5. Make sure that the current worksheet code editor is opened, and then copy and paste the below VBA code into it.

Code borrowed from extendoffice.com

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Update by Extendoffice: 2018/9/21
    Dim xCombox As OLEObject
    Dim xStr As String
    Dim xWs As Worksheet
    Dim xArr



    Set xWs = Application.ActiveSheet
    On Error Resume Next
    Set xCombox = xWs.OLEObjects("TempCombo")
    With xCombox
        .ListFillRange = ""
        .LinkedCell = ""
        .Visible = False
    End With
    If Target.Validation.Type = 3 Then
        Target.Validation.InCellDropdown = False
        Cancel = True
        xStr = Target.Validation.Formula1
        xStr = Right(xStr, Len(xStr) - 1)
        If xStr = "" Then Exit Sub
        With xCombox
            .Visible = True
            .Left = Target.Left
            .Top = Target.Top
            .Width = Target.Width + 5
            .Height = Target.Height + 5
            .ListFillRange = xStr
            If .ListFillRange = "" Then
                xArr = Split(xStr, ",")
                Me.TempCombo.List = xArr
            End If
            .LinkedCell = Target.Address
        End With
        xCombox.Activate
        Me.TempCombo.DropDown
    End If
End Sub

Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
        Case 9
            Application.ActiveCell.Offset(0, 1).Activate
        Case 13
            Application.ActiveCell.Offset(1, 0).Activate
    End Select
End Sub
  1. Click File > Close and Return to Microsoft Excel to close the Microsoft Visual Basic for Application window.

  2. Now, just click the cell with drop down list, you can see the drop-down list is displayed as a combo box, then type the first letter into the box, the corresponding word will be completed automatically.

Note: This VBA code is not applied to merged cells.

Source : How To Autocomplete When Typing In Excel Drop Down List?

How to send parameters from a notification-click to an activity?

Please use as PendingIntent while showing notification than it will be resolved.

PendingIntent intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Add PendingIntent.FLAG_UPDATE_CURRENT as last field.

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Unit testing private methods in C#

From the book Working Effectively with Legacy Code:

"If we need to test a private method, we should make it public. If making it public bothers us, in most cases, it means that our class is doing too much and we ought to fix it."

The way to fix it, according to the author, is by creating a new class and adding the method as public.

The author explains further:

"Good design is testable, and design that isn't testable is bad."

So, within these limits, your only real option is to make the method public, either in the current or a new class.

JavaScript: Object Rename Key

  • You can use a utility to handle this.
npm i paix
import { paix } from 'paix';

const source_object = { FirstName: "Jhon", LastName: "Doe", Ignored: true };
const replacement = { FirstName: 'first_name', LastName: 'last_name' };
const modified_object = paix(source_object, replacement);

console.log(modified_object);
// { Ignored: true, first_name: 'Jhon', last_name: 'Doe' };

fcntl substitute on Windows

The substitute of fcntl on windows are win32api calls. The usage is completely different. It is not some switch you can just flip.

In other words, porting a fcntl-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl call does and then find the equivalent win32api code, if any.

There's also the possibility that some code using fcntl has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.

If you provide more details about the fcntl calls people can find windows equivalents.

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

Where are $_SESSION variables stored?

As mentioned already, the contents are stored at the server. However the session is identified by a session-id, which is stored at the client and send with each request. Usually the session-id is stored in a cookie, but it can also be appended to urls. (That's the PHPSESSID query-parameter you some times see)

PHP: HTTP or HTTPS?

You should be able to do this by checking the value of $_SERVER['HTTPS'] (it should only be set when using https).

See http://php.net/manual/en/reserved.variables.server.php.

Find and extract a number from a string

Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

// Pull out only the numbers from the string using LINQ

var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());

var numericVal = Int32.Parse(numbersFromString);

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm no longer installs peer dependencies so you need to install them manually, just do an npm install on the needed deps, and then try to install the main one again.


Reply to comment:

it's right in that message, it says which deps you're missing

UNMET PEER DEPENDENCY angular-animate@^1.5.0 +-- 
UNMET PEER DEPENDENCY angular-aria@^1.5.0 +-- [email protected] +
UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]` 

So you need to npm install angular angular-animate angular-aria angular-material angular-messages mdi

Check whether $_POST-value is empty

To check if the property is present, irrespective of the value, use:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not null or false), use:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0 (integer), 0.0 (float), '0' (string), null, false or [] (empty array)), use:

if (!empty($_POST['userName'])) {}

SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show

Output:

echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

How do I block comment in Jupyter notebook?

Select the lines on windows jupyter notebook and then hit Ctrl+#.

How to add new item to hash

If you want to add new items from another hash - use merge method:

hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}

In your specific case it could be:

hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}

but it's not wise to use it when you should to add just one element more.

Pay attention that merge will replace the values with the existing keys:

hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}

exactly like hash[:item1] = 2

Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}

How to implement DrawerArrowToggle from Android appcompat v7 21 library

To answer the updated part of your question: to style the drawer icon/arrow, you have two options:

Style the arrow itself

To do this, override drawerArrowStyle in your theme like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/holo_purple</item>
    <!-- ^ this will make the icon purple -->
</style>

This is probably not what you want, because the ActionBar itself should have consistent styling with the arrow, so, most probably, you want the option two:

Theme the ActionBar/Toolbar

Override the android:actionBarTheme (actionBarTheme for appcompat) attribute of the global application theme with your own theme (which you probably should derive from ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar) like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@android:color/white</item>
    <!-- ^ this will make text and arrow white -->
    <!-- you can also override drawerArrowStyle here -->
</style>

An important note here is that when using a custom layout with a Toolbar instead of stock ActionBar implementation (e.g. if you're using the DrawerLayout-NavigationView-Toolbar combo to achieve the Material-style drawer effect where it's visible under translucent statusbar), the actionBarTheme attribute is obviosly not picked up automatically (because it's meant to be taken care of by the AppCompatActivity for the default ActionBar), so for your custom Toolbar don't forget to apply your theme manually:

<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme">

-- this will resolve to either AppCompat's default ThemeOverlay.AppCompat.ActionBar or your override if you set the attribute in your derived theme.

PS a little comment about the drawerArrowStyle override and the spinBars attribute -- which a lot of sources suggest should be set to true to get the drawer/arrow animation. Thing is, spinBars it is true by default in AppCompat (check out the Base.Widget.AppCompat.DrawerArrowToggle.Common style), you don't have to override actionBarTheme at all to get the animation working. You get the animation even if you do override it and set the attribute to false, it's just a different, less twirly animation. The important thing here is to use ActionBarDrawerToggle, it's what pulls in the fancy animated drawable.

xpath find if node exists

<xsl:if test="xpath-expression">...</xsl:if>

so for example

<xsl:if test="/html/body">body node exists</xsl:if>
<xsl:if test="not(/html/body)">body node missing</xsl:if>

How to get value of checked item from CheckedListBox?

foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}

How can I use optional parameters in a T-SQL stored procedure?

This also works:

    ...
    WHERE
        (FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
        (LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
        (Title IS NULL OR Title = ISNULL(@Title, Title))

Oracle SQL escape character (for a '&')

select 'one'||'&'||'two' from dual

The import com.google.android.gms cannot be resolved

Note that once you have imported the google-play-services_lib project into your IDE, you will also need to add google-play-services.jar to: Project=>Properties=>Java build path=>Libraries=>Add JARs

Set transparent background using ImageMagick and commandline prompt

I had the same problem. In which i have to remove white background from jpg/png image format using ImageMagick.

What worked for me was:

1) Convert image format to png: convert input.jpg input.png

2) convert input.png -fuzz 2% -transparent white output.png

Run a php app using tomcat?

A tad late, but here goes.

How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.

Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

public IList<Models.StandardRecipeDetail> GetRequisitionDetailBySearchCriteria(Guid subGroupItemId, Guid groupItemId)
{
    var query = this.UnitOfWork.Context.Database.SqlQuery<Models.StandardRecipeDetail>("SP_GetRequisitionDetailBySearchCriteria @SubGroupItemId,@GroupItemId",
    new System.Data.SqlClient.SqlParameter("@SubGroupItemId", subGroupItemId),
    new System.Data.SqlClient.SqlParameter("@GroupItemId", groupItemId));
    return query.ToList();
}

How can I convert tabs to spaces in every file of a directory?

No body mentioned rpl? Using rpl you can replace any string. To convert tabs to spaces,

rpl -R -e "\t" "    "  .

very simple.

anaconda - graphviz - can't import after installation

This command works officially for python:

conda install -c conda-forge python-graphviz

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

VBA setting the formula for a cell

Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.

strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address

The workbook and worksheet that strProjectName references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.

jQuery get content between <div> tags

jQuery has two methods

// First. Get content as HTML
$("#my_div_id").html();

// Second. Get content as text
$("#my_div_id").text();

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

jQuery select element in parent window

Use the context-parameter

$("#testdiv",parent.document)

But if you really use a popup, you need to access opener instead of parent

$("#testdiv",opener.document)

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

Most efficient way to find smallest of 3 numbers Java?

I would use min/max (and not worry otherwise) ... however, here is another "long hand" approach which may or may not be easier for some people to understand. (I would not expect it to be faster or slower than the code in the post.)

int smallest;
if (a < b) {
  if (a > c) {
    smallest = c;
  } else { // a <= c
    smallest = a;
  }
} else { // a >= b
  if (b > c) {
    smallest = c;
  } else { // b <= c
    smallest = b;
  }
}

Just throwing it into the mix.

Note that this is just the side-effecting variant of Abhishek's answer.

Insert a line break in mailto body

As per RFC2368 which defines mailto:, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A.

This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..

Make a link in the Android browser start up my app?

Once you have the intent and custom url scheme for your app set up, this javascript code at the top of a receiving page has worked for me on both iOS and Android:

<script type="text/javascript">
// if iPod / iPhone, display install app prompt
if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i) ||
    navigator.userAgent.match(/android/i)) {
  var store_loc = "itms://itunes.com/apps/raditaz";
  var href = "/iphone/";
  var is_android = false;
  if (navigator.userAgent.match(/android/i)) {
    store_loc = "https://play.google.com/store/apps/details?id=com.raditaz";
    href = "/android/";
    is_android = true;
  }
  if (location.hash) {
    var app_loc = "raditaz://" + location.hash.substring(2);
    if (is_android) {
      var w = null;
      try {
        w = window.open(app_loc, '_blank');
      } catch (e) {
        // no exception
      }
      if (w) { window.close(); }
      else { window.location = store_loc; }
    } else {
      var loadDateTime = new Date();
      window.setTimeout(function() {
        var timeOutDateTime = new Date();
        if (timeOutDateTime - loadDateTime < 5000) {
          window.location = store_loc;
        } else { window.close(); }
      },
      25);
      window.location = app_loc;
    }
  } else {
    location.href = href;
  }
}
</script>

This has only been tested on the Android browser. I am not sure about Firefox or Opera. The key is even though the Android browser will not throw a nice exception for you on window.open(custom_url, '_blank'), it will fail and return null which you can test later.

Update: using store_loc = "https://play.google.com/store/apps/details?id=com.raditaz"; to link to Google Play on Android.

How can I count all the lines of code in a directory recursively?

If you need just the total number of lines in, let's say, your PHP files, you can use very simple one line command even under Windows if you have GnuWin32 installed. Like this:

cat `/gnuwin32/bin/find.exe . -name *.php` | wc -l

You need to specify where exactly is the find.exe otherwise the Windows provided FIND.EXE (from the old DOS-like commands) will be executed, since it is probably before the GnuWin32 in the environment PATH and has different parameters and results.

Please note that in the command above you should use back-quotes, not single quotes.

Call JavaScript function from C#

If you want to call JavaScript function in C#, this will help you:

public string functionname(arg)
{
    if (condition)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        page.ClientScript.RegisterStartupScript(
            typeof(Page),
            "Test",
            "<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
    }
}

How to check what version of jQuery is loaded?

if (typeof jQuery != 'undefined') {  
    // jQuery is loaded => print the version
    alert(jQuery.fn.jquery);
}

Getting multiple keys of specified value of a generic Dictionary?

Can't you create a subclass of Dictionary which has that functionality?


    public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >
    {
        private Dictionary < TValue, TKey > _keys;

        public TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set 
            { 
                base[key] = value;
                _keys[value] = key;
            }
        }

        public MyDict()
        {
            _keys = new Dictionary < TValue, TKey >();
        }

        public TKey GetKeyFromValue(TValue value)
        {
            return _keys[value];
        }
    }

EDIT: Sorry, didn't get code right first time.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

Get webpage contents with Python?

Suppose you want to GET a webpage's content. The following code does it:

# -*- coding: utf-8 -*-
# python

# example of getting a web page

from urllib import urlopen
print urlopen("http://xahlee.info/python/python_index.html").read()

Move column by name to front of table in pandas

Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:

Column to the front:

df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]

Or if instead, you want to move it to the back:

df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]

Or if you wanted to move more than one column:

cols_to_move = ['Mid', 'Zsore']
df           = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]

Throughput and bandwidth difference?

Bandwidth is the maximum amount of data that can travel through a 'channel'.

Throughput is how much data actually does travel through the 'channel' successfully. This can be limited by a ton of different things including latency, and what protocol you are using.

"inconsistent use of tabs and spaces in indentation"

I got the same errors but could not figure out what I was doing wrong.

So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.

If anyone is wondering how I did that. Simple. Go in vim. Type in G=gg.

This will automatically fix everything. Good luck :)

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

How to convert wstring into string?

Here is a worked-out solution based on the other suggestions:

#include <string>
#include <iostream>
#include <clocale>
#include <locale>
#include <vector>

int main() {
  std::setlocale(LC_ALL, "");
  const std::wstring ws = L"hëllö";
  const std::locale locale("");
  typedef std::codecvt<wchar_t, char, std::mbstate_t> converter_type;
  const converter_type& converter = std::use_facet<converter_type>(locale);
  std::vector<char> to(ws.length() * converter.max_length());
  std::mbstate_t state;
  const wchar_t* from_next;
  char* to_next;
  const converter_type::result result = converter.out(state, ws.data(), ws.data() + ws.length(), from_next, &to[0], &to[0] + to.size(), to_next);
  if (result == converter_type::ok or result == converter_type::noconv) {
    const std::string s(&to[0], to_next);
    std::cout <<"std::string =     "<<s<<std::endl;
  }
}

This will usually work for Linux, but will create problems on Windows.

How to create JNDI context in Spring Boot with Embedded Tomcat Container

After all i got the answer thanks to wikisona, first the beans:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

        @Override
        protected void postProcessContext(Context context) {
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "your.db.Driver");
            resource.setProperty("url", "jdbc:yourDb");

            context.getNamingResources().addResource(resource);
        }
    };
}

@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi

JavaScript code to stop form submission

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

Had just to ponder that same question (on Windows-side, but equally applicable to linux.) Suprisingly nobody mentioned a very much automated way of doing CRLF<->LF conversion for text-files using good old zip -ll option (Info-ZIP):

zip -ll textfiles-lf.zip files-with-crlf-eol.*
unzip textfiles-lf.zip 

NOTE: this would create a zip file preserving the original file names but converting the line endings to LF. Then unzip would extract the files as zip'ed, that is with their original names (but with LF-endings), thus prompting to overwrite the local original files if any.

Relevant excerpt from the zip --help:

zip --help
...
-l   convert LF to CR LF (-ll CR LF to LF)

Convert bytes to int?

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

Which comment style should I use in batch files?

This page tell that using "::" will be faster under certain constraints Just a thing to consider when choosing

How to send string from one activity to another?

For those people who use Kotlin do this instead:

  1. Create a method with a parameter containing String Object.
  2. Navigate to another Activity

For Example,


// * The Method I Mentioned Above 
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
     val intent = Intent(this, AnotherActivity::class.java)
     intent.putExtra("value", valueYouWantToParse)
     intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
     startActivity(intent)
     this.finish()
}

Then just call parseTheValue("the String that you want to parse")

e.g,

val theValue: String
 parseTheValue(theValue)

then in the other activity,

val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()

// * For testing
println(str)

Hope This Help, Happy Coding!

~ Kotlin Code Added By John Melody~

How do I run a terminal inside of Vim?

Split the screen and run command term ++curwin to run the terminal inside the Vim buffer. Following command does both and worked for me:

:bo 10sp | term ++curwin

How to add header row to a pandas DataFrame

To fix your code you can simply change [Cov] to Cov.values, the first parameter of pd.DataFrame will become a multi-dimensional numpy array:

Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')

But the smartest solution still is use pd.read_excel with header=None and names=columns_list.

Fill Combobox from database

Out side the loop, set following.

cmbTripName.ValueMember = "FleetID"
cmbTripName.DisplayMember = "FleetName"

Use index in pandas to plot data

You can use reset_index to turn the index back into a column:

monthly_mean.reset_index().plot(x='index', y='A')

How to create a hex dump of file containing only the hex characters without spaces in bash?

The other answers are preferable, but for a pure Bash solution, I've modified the script in my answer here to be able to output a continuous stream of hex characters representing the contents of a file. (Its normal mode is to emulate hexdump -C.)

Environment Variable with Maven

I suggest using the amazing tool direnv. With it you can inject environment variables once you cd into the project. These steps worked for me:

.envrc file

source_up
dotenv

.env file

_JAVA_OPTIONS="-DYourEnvHere=123"

Headers and client library minor version mismatch

Warning: mysqli::mysqli(): Headers and client library minor version mismatch.
Headers:50547 Library:100026

I solved the above error by just rebuilding my Apache:

cPanel Version  56.0 (build 25)
Apache Version  2.4.18
PHP Version 5.5.30
MySQL Version   10.0.26-MariaDB

eval command in Bash and its typical uses

In the question:

who | grep $(tty | sed s:/dev/::)

outputs errors claiming that files a and tty do not exist. I understood this to mean that tty is not being interpreted before execution of grep, but instead that bash passed tty as a parameter to grep, which interpreted it as a file name.

There is also a situation of nested redirection, which should be handled by matched parentheses which should specify a child process, but bash is primitively a word separator, creating parameters to be sent to a program, therefore parentheses are not matched first, but interpreted as seen.

I got specific with grep, and specified the file as a parameter instead of using a pipe. I also simplified the base command, passing output from a command as a file, so that i/o piping would not be nested:

grep $(tty | sed s:/dev/::) <(who)

works well.

who | grep $(echo pts/3)

is not really desired, but eliminates the nested pipe and also works well.

In conclusion, bash does not seem to like nested pipping. It is important to understand that bash is not a new-wave program written in a recursive manner. Instead, bash is an old 1,2,3 program, which has been appended with features. For purposes of assuring backward compatibility, the initial manner of interpretation has never been modified. If bash was rewritten to first match parentheses, how many bugs would be introduced into how many bash programs? Many programmers love to be cryptic.

ruby LoadError: cannot load such file

The problem shall have solved if you specify your path.

e.g.

"require 'st.rb'" --> "require './st.rb'"

See if your problem get solved or not.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I would urge against using OleDB, especially if its going to be run on a server. Its likely to cost you more in the long run - eg we had a SSIS job calling a Stored Procedure with the OleDB reading an excel file in the sptroc and kept crashing the SQL box! I took the OleDB stuff out of the sproc and it stopped crashing the server.

A better method I've found is to do it with Office 2003 and the XML files - in respect of Considerations for server-side Automation of Office. Note: Office 2003 is a minimum requirement for this to fly:

Ref for reading from Excel: http://www.roelvanlisdonk.nl/?p=924 (please do more research to find other examples)

Ref for writing a Excel spreadsheet: http://weblogs.asp.net/jgaylord/archive/2008/08/11/use-linq-to-xml-to-generate-excel-documents.aspx

public void ReadExcelCellTest()
        {
            XDocument document = XDocument.Load(@"C:\BDATA\Cars.xml");
            XNamespace workbookNameSpace = @"urn:schemas-microsoft-com:office:spreadsheet";

            // Get worksheet
            var query = from w in document.Elements(workbookNameSpace + "Workbook").Elements(workbookNameSpace + "Worksheet")
                        where w.Attribute(workbookNameSpace + "Name").Value.Equals("Settings")
                        select w;
            List<XElement> foundWoksheets = query.ToList<XElement>();
            if (foundWoksheets.Count() <= 0) { throw new ApplicationException("Worksheet Settings could not be found"); }
            XElement worksheet = query.ToList<XElement>()[0];

            // Get the row for "Seat"
            query = from d in worksheet.Elements(workbookNameSpace + "Table").Elements(workbookNameSpace + "Row").Elements(workbookNameSpace + "Cell").Elements(workbookNameSpace + "Data")
                    where d.Value.Equals("Seat")
                    select d;
            List<XElement> foundData = query.ToList<XElement>();
            if (foundData.Count() <= 0) { throw new ApplicationException("Row 'Seat' could not be found"); }
            XElement row = query.ToList<XElement>()[0].Parent.Parent;

            // Get value cell of Etl_SPIImportLocation_ImportPath setting
            XElement cell = row.Elements().ToList<XElement>()[1];

            // Get the value "Leon"
            string cellValue = cell.Elements(workbookNameSpace + "Data").ToList<XElement>()[0].Value;

            Console.WriteLine(cellValue);
        }

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

How to simulate target="_blank" in JavaScript

I know this is a done and sorted out deal, but here's what I'm using to solve the problem in my app.

if (!e.target.hasAttribute("target")) {
    e.preventDefault();     
    e.target.setAttribute("target", "_blank");
    e.target.click();
    return;
}

Basically what is going on here is I run a check for if the link has target=_blank attribute. If it doesn't, it stops the link from triggering, sets it up to open in a new window then programmatically clicks on it.

You can go one step further and skip the stopping of the original click (and make your code a whole lot more compact) by trying this:

if (!e.target.hasAttribute("target")) {
    e.target.setAttribute("target", "_blank");
}

If you were using jQuery to abstract away the implementation of adding an attribute cross-browser, you should use this instead of e.target.setAttribute("target", "_blank"):

    jQuery(event.target).attr("target", "_blank")

You may need to rework it to fit your exact use-case, but here's how I scratched my own itch.

Here's a demo of it in action for you to mess with.

(The link in jsfiddle comes back to this discussion .. no need a new tab :))

How to sum a list of integers with java streams?

class Pojo{
    int num;

    public Pojo(int num) {
        super();
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}

List<Pojo> list = new ArrayList<Pojo>();
            list.add(new Pojo(1));
            list.add(new Pojo(5));
            list.add(new Pojo(3));
            list.add(new Pojo(4));
            list.add(new Pojo(5));

            int totalSum = list.stream().mapToInt(pojo -> pojo.getNum()).sum();
            System.out.println(totalSum);

current/duration time of html5 video?

https://www.w3schools.com/tags/av_event_timeupdate.asp

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;
}

Why both no-cache and no-store should be used in HTTP response?

I must clarify that no-cache does not mean do not cache. In fact, it means "revalidate with server" before using any cached response you may have, on every request.

must-revalidate, on the other hand, only needs to revalidate when the resource is considered stale.

If the server says that the resource is still valid then the cache can respond with its representation, thus alleviating the need for the server to resend the entire resource.

no-store is effectively the full do not cache directive and is intended to prevent storage of the representation in any form of cache whatsoever.

I say whatsoever, but note this in the RFC 2616 HTTP spec:

History buffers MAY store such responses as part of their normal operation

But this is omitted from the newer RFC 7234 HTTP spec in potentially an attempt to make no-store stronger, see:

http://tools.ietf.org/html/rfc7234#section-5.2.1.5

What does "all" stand for in a makefile?

The manual for GNU Make gives a clear definition for all in its list of standard targets.

If the author of the Makefile is following that convention then the target all should:

  1. Compile the entire program, but not build documentation.
  2. Be the the default target. As in running just make should do the same as make all.

To achieve 1 all is typically defined as a .PHONY target that depends on the executable(s) that form the entire program:

.PHONY : all
all : executable

To achieve 2 all should either be the first target defined in the make file or be assigned as the default goal:

.DEFAULT_GOAL := all

Query to get only numbers from a string

Firstly find out the number's starting length then reverse the string to find out the first position again(which will give you end position of number from the end). Now if you deduct 1 from both number and deduct it from string whole length you'll get only number length. Now get the number using SUBSTRING

declare @fieldName nvarchar(100)='AAAA1221.121BBBB'

declare @lenSt int=(select PATINDEX('%[0-9]%', @fieldName)-1)
declare @lenEnd int=(select PATINDEX('%[0-9]%', REVERSE(@fieldName))-1)

select SUBSTRING(@fieldName, PATINDEX('%[0-9]%', @fieldName), (LEN(@fieldName) - @lenSt -@lenEnd))

How do I write a correct micro-benchmark in Java?

jmh is a recent addition to OpenJDK and has been written by some performance engineers from Oracle. Certainly worth a look.

The jmh is a Java harness for building, running, and analysing nano/micro/macro benchmarks written in Java and other languages targetting the JVM.

Very interesting pieces of information buried in the sample tests comments.

See also:

How do I get a reference to the app delegate in Swift?

it is very simple

App delegate instance

let app = UIApplication.shared.delegate as! AppDelegate

you can call a method with one line syntax

app.callingMethod()

you can access a variable with this code

app.yourVariable = "Assigning a value"

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Bitbucket supports a REST API you can use to programmatically create Bitbucket repositories.

Documentation and cURL sample available here: https://confluence.atlassian.com/bitbucket/repository-resource-423626331.html#repositoryResource-POSTanewrepository

$ curl -X POST -v -u username:password -H "Content-Type: application/json" \
   https://api.bitbucket.org/2.0/repositories/teamsinspace/new-repository4 \
   -d '{"scm": "git", "is_private": "true", "fork_policy": "no_public_forks" }'

Under Windows, curl is available from the Git Bash shell.

Using this method you could easily create a script to import many repos from a local git server to Bitbucket.

iterating through Enumeration of hastable keys throws NoSuchElementException error

for (String key : Collections.list(e))
    System.out.println(key);

In Laravel, the best way to pass different types of flash messages in the session

Another solution would be to create a helper class How to Create helper classes here

class Helper{
     public static function format_message($message,$type)
    {
         return '<p class="alert alert-'.$type.'">'.$message.'</p>'
    }
}

Then you can do this.

Redirect::to('users/login')->with('message', Helper::format_message('A bla blah occured','error'));

or

Redirect::to('users/login')->with('message', Helper::format_message('Thanks for registering!','info'));

and in your view

@if(Session::has('message'))
    {{Session::get('message')}}
@endif

How do you input command line arguments in IntelliJ IDEA?

Main Program -> Run -> Edit Configurations -> Inside Configuration there is Program arguments text box. add space separated argument in the text box. Then you can read those arguments in the args array (public static void main(String[] args))

Angularjs autocomplete from $http

Use angular-ui-bootstrap's typehead.

It had great support for $http and promises. Also, it doesn't include any JQuery at all, pure AngularJS.

(I always prefer using existing libraries and if they are missing something to open an issue or pull request, much better then creating your own again)

PHP - auto refreshing page

<meta http-equiv="refresh" content="10" >

This can work. Try it..!! :-)

Pointer to class data member "::*"

I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.

SharePoint : How can I programmatically add items to a custom list instance

I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),

1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install

2- Add "using Microsoft.SharePoint.Client; "

then the below code

        string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
        SecureString passWord = new SecureString();

        var password = "Your password here";
        var securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
        List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
        ListItem oListItem = oList.AddItem(itemCreateInfo);
        oListItem["PK"] = "1";
        oListItem["Precinct"] = "Mangere";
        oListItem["Title"] = "Innovation";
        oListItem["Project_x005F_x0020_Name"] = "test from C#";
        oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
        oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
        oListItem.Update();

        clientContext.ExecuteQuery();

Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?

A few approaches:

1- Use MS flow and see them

2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column

3- Use a C# reader and read your sharepoint list

The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)

Method List in Visual Studio Code

Update: As stated in the comments by @jeff-xiao this extension is Deprecated and it's now a built in feature of Visual Studio code. It should be available at the bottom of file explorer as "Outline" view.

Previous text: There is now an Extension that supports this. Code Outline creates a panel in the "Explorer" section and for JavaScript, will list variables and functions in a file. I've been using this for a while now and it scratches the itch I had. Other commenters have mentioned it supports Python and PHP well.

It still seems to be in development but I haven't had any issues. Development version available on GitHub. If you're the author reading this - thanks!

This is how it looks:
Code Outline plugin for VSCode

If Code Outline is not visible, you can show it by: enter image description here

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("new").show();

$("new").hide();

w3cSchool link to JQuery show and hide

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

Convert a video to MP4 (H.264/AAC) with ffmpeg

Software patents led Debian/Ubuntu to disable the H.264 and AAC encoders in ffmpeg. See /usr/share/doc/ffmpeg/README.Debian.gz.

So go install x264, mplayer/mencoder, and Nero's AAC encoder. (Or, if you want to use all Free software, and don't care so much about audio quality, then sudo aptitude install faac.)

I don't remember if the medibuntu package of mencoder includes x264 vid encoding, since I build my own from git x264 and svn mplayer sources. (x264 is very actively developed, with significant quality and speed improvements frequently added.) http://git.videolan.org/?p=x264.git;a=summary

x264 is also packaged, but you should check that it's up to date enough to include weightp with recent bugfixes, and even more recent speed improvements...

Or if you're already willing to convert from .flv, instead of going from the high-quality source the flv was made from, then probably whatever recent version of x264 you can find will be fine.

Easy way to get a test file into JUnit

I know you said you didn't want to read the file in by hand, but this is pretty easy

public class FooTest
{
    private BufferedReader in = null;

    @Before
    public void setup()
        throws IOException
    {
        in = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/data.txt")));
    }

    @After
    public void teardown()
        throws IOException
    {
        if (in != null)
        {
            in.close();
        }

        in = null;
    }

    @Test
    public void testFoo()
        throws IOException
    {
        String line = in.readLine();

        assertThat(line, notNullValue());
    }
}

All you have to do is ensure the file in question is in the classpath. If you're using Maven, just put the file in src/test/resources and Maven will include it in the classpath when running your tests. If you need to do this sort of thing a lot, you could put the code that opens the file in a superclass and have your tests inherit from that.

Get a JSON object from a HTTP response

You need to use JSONObject like below:

String mJsonString = downloadFileFromInternet(urls[0]);

JSONObject jObject = null;
try {
    jObject = new JSONObject(mJsonString);
} 
catch (JSONException e) {
    e.printStackTrace();
    return false;
}

...

private String downloadFileFromInternet(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        new IllegalArgumentException("url is empty/null");
    StringBuilder sb = new StringBuilder();
    InputStream inStream = null;
    try
    {
        url = urlEncode(url);
        URL link = new URL(url);
        inStream = link.openStream();
        int i;
        int total = 0;
        byte[] buffer = new byte[8 * 1024];
        while((i=inStream.read(buffer)) != -1)
        {
            if(total >= (1024 * 1024))
            {
                return "";
            }
            total += i;
            sb.append(new String(buffer,0,i));
        }
    }
    catch(Exception e )
    {
        e.printStackTrace();
        return null;
    }catch(OutOfMemoryError e)
    {
        e.printStackTrace();
        return null;
    }
    return sb.toString();
}

private String urlEncode(String url)
{
    if(url == null /*|| url.isEmpty() == true*/)
        return null;
    url = url.replace("[","");
    url = url.replace("]","");
    url = url.replaceAll(" ","%20");
    return url;
}

Hope this helps you..

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

I think that the best solution is to use java.sql.Savepoint.

Before you execute a query which can throw SQLException, use the method Connection.setSavepoint(), and if an exception is thrown you only rollback to this savepoint, not the whole transaction.

Example code:

Connection conn = null;
Savepoint savepoint = null;
try {
    conn = getConnection();
    savepoint = conn.setSavepoint();
    //execute some query
} catch(SQLException e) {
    if(conn != null && savepoint != null) {
        conn.rollback(savepoint);
    }
} finally {
   if(conn != null) {
      try {
          conn.close();
      } catch(SQLException e) {}

   }
}

key_load_public: invalid format

So, after update I had the same issue. I was using PEM key_file without extension and simply adding .pem fixed my issue. Now the file is key_file.pem.

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

Trigger an action after selection select2

This worked for me (Select2 4.0.4):

$(document).on('change', 'select#your_id', function(e) {
    // your code
    console.log('this.value', this.value);
});

Finding repeated words on a string and counting the repetitions

Using java8

private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

Also, use a LinkedHashMap if you want to preserve the order of insertion

private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

Output

[House, Dog]
[3, 4]

Save plot to image file instead of displaying it using Matplotlib

Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

in my case i made a custom view i added to custom view constructor

new RoomView(getAplicationContext());

the correct context is activity so changed it to:

new RoomView(getActivity());

or

new RoomView(this);

How can I validate a string to only allow alphanumeric characters in it?

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23".IsAlphaNumeric() will return True whereas "smith 23".IsAlphaNumeric(false) will return False. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden as shown above. If you want to allow spaces such that "smith 23".IsAlphaNumeric() will return True, simple default the arg.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

Wait for a void async method

I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.

However, I noticed that .Wait() is working properly inside the void method.

and since async void and void have the same signature, you might need to do the following.

void LoadBlahBlah()
{
    blah().Wait(); //this blocks
}

Confusingly enough async/await does not block on the next code.

async void LoadBlahBlah()
{
    await blah(); //this does not block
}

When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks

this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.

So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.

hopefully my rambling makes sense to anybody also looking for answers.

Edit: I made some example code and decompiled it to see what is actually going on.

static async void Test()
{
    await Task.Delay(5000);
}

static async Task TestAsync()
{
    await Task.Delay(5000);
}

Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)

private static void Test()
{
    <Test>d__1 stateMachine = new <Test>d__1();
    stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
    <TestAsync>d__2 stateMachine = new <TestAsync>d__2();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.

meaning without the returning Task, there would be no way to check if it is complete.

as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.

so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.

alert a variable value

If I'm understanding your question and code correctly, then I want to first mention three things before sharing my code/version of a solution. First, for both name and value you probably shouldn't be using the getAttribute() method because they are, themselves, properties of (the variable named) inputs (at a given index of i). Secondly, the variable that you are trying to alert is one of a select handful of terms in JavaScript that are designated as 'reserved keywords' or simply "reserved words". As you can see in/on this list (on the link), new is clearly a reserved word in JS and should never be used as a variable name. For more information, simply google 'reserved words in JavaScript'. Third and finally, in your alert statement itself, you neglected to include a semicolon. That and that alone can sometimes be enough for your code not to run as expected. [Aside: I'm not saying this as advice but more as observation: JavaScript will almost always forgive and allow having too many and/or unnecessary semicolons, but generally JavaScript is also equally if not moreso merciless if/when missing (any of the) necessary, required semicolons. Therefore, best practice is, of course, to add the semicolons only at all of the required points and exclude them in all other circumstances. But practically speaking, if in doubt, it probably will not hurt things by adding/including an extra one but will hurt by ignoring a mandatory one. General rules are all declarations and assignments end with a semicolon (such as variable assignments, alerts, console.log statements, etc.) but most/all expressions do not (such as for loops, while loops, function expressions Just Saying.] But I digress..

    function whenWindowIsReady() {
        var inputs = document.getElementsByTagName('input');
        var lengthOfInputs = inputs.length; // this is for optimization
        for (var i = 0; i < lengthOfInputs; i++) {
            if (inputs[i].name === "ans") {   
                var ansIsName = inputs[i].value;
                alert(ansIsName);
            }
        }
    }

    window.onReady = whenWindowIsReady();

PS: You used a double assignment operator in your conditional statement, and in this case it doesn't matter since you are comparing Strings, but generally I believe the triple assignment operator is the way to go and is more accurate as that would check if the values are EQUIVALENT WITHOUT TYPE CONVERSION, which can be very important for other instances of comparisons, so it's important to point out. For example, 1=="1" and 0==false are both true (when usually you'd want those to return false since the value on the left was not the same as the value on the right, without type conversion) but 1==="1" and 0===false are both false as you'd expect because the triple operator doesn't rely on type conversion when making comparisons. Keep that in mind for the future.

How to get indices of a sorted array in Python

Something like next:

>>> myList = [1, 2, 3, 100, 5]
>>> [i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])]
[0, 1, 2, 4, 3]

enumerate(myList) gives you a list containing tuples of (index, value):

[(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)]

You sort the list by passing it to sorted and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...] list comprehension.

How to count lines in a document?

wc -l <file.txt>

Or

command | wc -l

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

How can I strip first and last double quotes?

in your example you could use strip but you have to provide the space

string = '"" " " ""\\1" " "" ""'
string.strip('" ')  # output '\\1'

note the \' in the output is the standard python quotes for string output

the value of your variable is '\\1'

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

HTTP 404 when accessing .svc file in IIS

I had to add the extension .svc to the allowed extensions in the request filtering settings (got 404.7 errors before).

enter image description here

How to fix getImageData() error The canvas has been tainted by cross-origin data?

I found that I had to use .setAttribute('crossOrigin', '') and had to append a timestamp to the URL's query string to avoid a 304 response lacking the Access-Control-Allow-Origin header.

This gives me

var url = 'http://lorempixel.com/g/400/200/';
var imgObj = new Image();
imgObj.src = url + '?' + new Date().getTime();
imgObj.setAttribute('crossOrigin', '');

When to use EntityManager.find() vs EntityManager.getReference() with JPA

Because a reference is 'managed', but not hydrated, it can also allow you to remove an entity by ID, without needing to load it into memory first.

As you can't remove an unmanaged entity, it's just plain silly to load all fields using find(...) or createQuery(...), only to immediately delete it.

MyLargeObject myObject = em.getReference(MyLargeObject.class, objectId);
em.remove(myObject);

How to join two sets in one line without using "|"

You can do union or simple list comprehension

[A.add(_) for _ in B]

A would have all the elements of B

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

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.

What does ':' (colon) do in JavaScript?

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

Get a DataTable Columns DataType

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

When to use static keyword before global variables?

static renders variable local to the file which is generally a good thing, see for example this Wikipedia entry.

Fetch first element which matches criteria

This might be what you are looking for:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .get();

And better, if there's a possibility of matching no element, in which case get() will throw a NPE. So use:

yourStream
    .filter(/* your criteria */)
    .findFirst()
    .orElse(null); /* You could also create a default object here */


An example:
public static void main(String[] args) {
    class Stop {
        private final String stationName;
        private final int    passengerCount;

        Stop(final String stationName, final int passengerCount) {
            this.stationName    = stationName;
            this.passengerCount = passengerCount;
        }
    }

    List<Stop> stops = new LinkedList<>();

    stops.add(new Stop("Station1", 250));
    stops.add(new Stop("Station2", 275));
    stops.add(new Stop("Station3", 390));
    stops.add(new Stop("Station2", 210));
    stops.add(new Stop("Station1", 190));

    Stop firstStopAtStation1 = stops.stream()
            .filter(e -> e.stationName.equals("Station1"))
            .findFirst()
            .orElse(null);

    System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}

Output is:

At the first stop at Station1 there were 250 passengers in the train.

Conditional formatting using AND() function

I am currently responsible for an Excel application with a lot of legacy code. One of the slowest pieces of this code was looping through 500 Rows in 6 Columns, setting conditional formatting formulae for each. The formulae are to identify where the cell contents are non-blank but do not form part of a Named Range, therefore referring twice to the cell itself, originally written as:

=AND(COUNTIF(<rangename>,<cellref>)=0,<cellref><>"")

Obviously the overheads would be much reduced by updating all Cells in each Column (Range) at once. However, as noted above, using ADDRESS(ROW(),COLUMN(),n) does not work in this circumstance, i.e. this does not work:

=AND(COUNTIF(<rangename>,ADDRESS(ROW(),COLUMN(),1))=0,ADDRESS(ROW(),COLUMN(),1)<>"")

I experimented extensively with a blank workbook and could find no way around this, using various alternatives such as ISBLANK. In the end, to get around this, I created two User-Defined Functions (using a tip I found elsewhere on this site):

Public Function returnCellContent() As Variant

  returnCellContent = Application.Caller.Value

End Function

Public Function Cell_HasContent() As Boolean

  If Application.Caller.Value = "" Then
    Cell_HasContent = False
  Else
    Cell_HasContent = True
  End If

End Function

The conditional formula is now:

=AND(COUNTIF(<rangename>,returnCellContent()=0,Cell_HasContent())

which works fine.

This has sped the code up, in Excel 2010, from 5s to 1s. Because this code is run whenever data is loaded into the application, this saving is significant and noticeable to the user. It's also a lot cleaner and reusable.

I've taken the time to post this because I could not find any answers on this site or elsewhere that cover all of the circumstances, whilst I'm sure that there are others who could benefit from the above approach, potentially with much larger numbers of cells to update.