Programs & Examples On #Shotgun

Shotgun is a Ruby gem, an automatically reloading version of the rackup command that's shipped with Rack.

Which Ruby version am I really running?

If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION.

Tomcat 7 "SEVERE: A child container failed during start"

you can fix it with:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>${servlet-api-version}</version>
    <scope>provided</scope>
</dependency>

provided solves this problem

Tomcat manager/html is not available?

After entering the roles and users in tomcat-users still if does not work make sure your tomact server location point to the right server location

Using variable in SQL LIKE statement

This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:

declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'

Best way to get value from Collection by index

It would be just as convenient to simply convert your collection into a list whenever it updates. But if you are initializing, this will suffice:

for(String i : collectionlist){
    arraylist.add(i);
    whateverIntID = arraylist.indexOf(i);
}

Be open-minded.

Difference between arguments and parameters in Java

Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.

You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done

How to debug stored procedures with print statements?

Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.

Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.

  • For even more opinions/observations focus your attention on this SO post here.
  • Specifically look at this answer of the same post by Phil_factor (Ha ha! Love the SQL humor)
  • Regarding the suggestion of using RAISERROR WITH NOWAIT look at this answer of the same post by JimCarden

Don't do these things

  1. Some people are under the impression that they can just use a GO statement after their PRINT statement, but you CANNOT use the GO statement INSIDE of a sproc. So that solution is out.
  2. I don't recommend SELECT-ing your print statements because it is just going to muddy your result set with nonsense and if your sproc is supposed to be consumed by a program later, then you will have to know which result sets to skip when looping through the results from your data reader. This is just a bad idea, so don't do it.
  3. Another problem with SELECT-ING your print statements is that they don't always show up immediately. I have had different experiences with this for different executions, so don't expect any kind of consistency with this methodology.

Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...

It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
    SET NOCOUNT ON;

    -- This will print immediately
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    -- Five second delay to simulate lengthy execution
    WAITFOR DELAY '00:00:05'

    -- This will print after the five second delay
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample]

Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.

Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
    SET NOCOUNT ON;

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P Start';
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    WAITFOR DELAY '00:00:05'

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P End'
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample2]

Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

what is the difference between json and xml

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

setting global sql_mode in mysql

I resolved it.

the correct mode is :

set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Java URL encoding of query string parameters

I would not use URLEncoder. Besides being incorrectly named (URLEncoder has nothing to do with URLs), inefficient (it uses a StringBuffer instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.

Instead I would use URIBuilder or Spring's org.springframework.web.util.UriUtils.encodeQuery or Commons Apache HttpClient. The reason being you have to escape the query parameters name (ie BalusC's answer q) differently than the parameter value.

The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.

Sample code:

import org.apache.http.client.utils.URIBuilder;

URIBuilder ub = new URIBuilder("http://example.com/query");
ub.addParameter("q", "random word £500 bank \$");
String url = ub.toString();

// Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24

Since I'm just linking to other answers I marked this as a community wiki. Feel free to edit.

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

how to parse xml to java object?

JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,

<customer id="100">
    <age>29</age>
    <name>mkyong</name>
</customer>

Create necessary model class(es):

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

Try to unmarshal:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

Check results, fix bugs!

CSS3 transform not working

-webkit-transform is no more needed

ms already support rotation ( -ms-transform: rotate(-10deg); )

try this:

li a {
   ...

    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
    }

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

The following method is about 30 times faster than scipy.spatial.distance.pdist. It works pretty quickly on large matrices (assuming you have enough RAM)

See below for a discussion of how to optimize for sparsity.

# base similarity matrix (all dot products)
# replace this with A.dot(A.T).toarray() for sparse representation
similarity = numpy.dot(A, A.T)


# squared magnitude of preference vectors (number of occurrences)
square_mag = numpy.diag(similarity)

# inverse squared magnitude
inv_square_mag = 1 / square_mag

# if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
inv_square_mag[numpy.isinf(inv_square_mag)] = 0

# inverse of the magnitude
inv_mag = numpy.sqrt(inv_square_mag)

# cosine similarity (elementwise multiply by inverse magnitudes)
cosine = similarity * inv_mag
cosine = cosine.T * inv_mag

If your problem is typical for large scale binary preference problems, you have a lot more entries in one dimension than the other. Also, the short dimension is the one whose entries you want to calculate similarities between. Let's call this dimension the 'item' dimension.

If this is the case, list your 'items' in rows and create A using scipy.sparse. Then replace the first line as indicated.

If your problem is atypical you'll need more modifications. Those should be pretty straightforward replacements of basic numpy operations with their scipy.sparse equivalents.

Compare DATETIME and DATE ignoring time portion

Use the CAST to the new DATE data type in SQL Server 2008 to compare just the date portion:

IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)

Purpose of returning by const value?

It's pretty pointless to return a const value from a function.

It's difficult to get it to have any effect on your code:

const int foo() {
   return 3;
}

int main() {
   int x = foo();  // copies happily
   x = 4;
}

and:

const int foo() {
   return 3;
}

int main() {
   foo() = 4;  // not valid anyway for built-in types
}

// error: lvalue required as left operand of assignment

Though you can notice if the return type is a user-defined type:

struct T {};

const T foo() {
   return T();
}

int main() {
   foo() = T();
}

// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers

it's questionable whether this is of any benefit to anyone.

Returning a reference is different, but unless Object is some template parameter, you're not doing that.

ipynb import another ipynb file

Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well. Thanks all!

Controlling fps with requestAnimationFrame?

Update 2016/6

The problem throttling the frame rate is that the screen has a constant update rate, typically 60 FPS.

If we want 24 FPS we will never get the true 24 fps on the screen, we can time it as such but not show it as the monitor can only show synced frames at 15 fps, 30 fps or 60 fps (some monitors also 120 fps).

However, for timing purposes we can calculate and update when possible.

You can build all the logic for controlling the frame-rate by encapsulating calculations and callbacks into an object:

function FpsCtrl(fps, callback) {

    var delay = 1000 / fps,                               // calc. time per frame
        time = null,                                      // start time
        frame = -1,                                       // frame count
        tref;                                             // rAF time reference

    function loop(timestamp) {
        if (time === null) time = timestamp;              // init start time
        var seg = Math.floor((timestamp - time) / delay); // calc frame no.
        if (seg > frame) {                                // moved to next frame?
            frame = seg;                                  // update
            callback({                                    // callback function
                time: timestamp,
                frame: frame
            })
        }
        tref = requestAnimationFrame(loop)
    }
}

Then add some controller and configuration code:

// play status
this.isPlaying = false;

// set frame-rate
this.frameRate = function(newfps) {
    if (!arguments.length) return fps;
    fps = newfps;
    delay = 1000 / fps;
    frame = -1;
    time = null;
};

// enable starting/pausing of the object
this.start = function() {
    if (!this.isPlaying) {
        this.isPlaying = true;
        tref = requestAnimationFrame(loop);
    }
};

this.pause = function() {
    if (this.isPlaying) {
        cancelAnimationFrame(tref);
        this.isPlaying = false;
        time = null;
        frame = -1;
    }
};

Usage

It becomes very simple - now, all that we have to do is to create an instance by setting callback function and desired frame rate just like this:

var fc = new FpsCtrl(24, function(e) {
     // render each frame here
  });

Then start (which could be the default behavior if desired):

fc.start();

That's it, all the logic is handled internally.

Demo

_x000D_
_x000D_
var ctx = c.getContext("2d"), pTime = 0, mTime = 0, x = 0;_x000D_
ctx.font = "20px sans-serif";_x000D_
_x000D_
// update canvas with some information and animation_x000D_
var fps = new FpsCtrl(12, function(e) {_x000D_
 ctx.clearRect(0, 0, c.width, c.height);_x000D_
 ctx.fillText("FPS: " + fps.frameRate() + _x000D_
                 " Frame: " + e.frame + _x000D_
                 " Time: " + (e.time - pTime).toFixed(1), 4, 30);_x000D_
 pTime = e.time;_x000D_
 var x = (pTime - mTime) * 0.1;_x000D_
 if (x > c.width) mTime = pTime;_x000D_
 ctx.fillRect(x, 50, 10, 10)_x000D_
})_x000D_
_x000D_
// start the loop_x000D_
fps.start();_x000D_
_x000D_
// UI_x000D_
bState.onclick = function() {_x000D_
 fps.isPlaying ? fps.pause() : fps.start();_x000D_
};_x000D_
_x000D_
sFPS.onchange = function() {_x000D_
 fps.frameRate(+this.value)_x000D_
};_x000D_
_x000D_
function FpsCtrl(fps, callback) {_x000D_
_x000D_
 var delay = 1000 / fps,_x000D_
  time = null,_x000D_
  frame = -1,_x000D_
  tref;_x000D_
_x000D_
 function loop(timestamp) {_x000D_
  if (time === null) time = timestamp;_x000D_
  var seg = Math.floor((timestamp - time) / delay);_x000D_
  if (seg > frame) {_x000D_
   frame = seg;_x000D_
   callback({_x000D_
    time: timestamp,_x000D_
    frame: frame_x000D_
   })_x000D_
  }_x000D_
  tref = requestAnimationFrame(loop)_x000D_
 }_x000D_
_x000D_
 this.isPlaying = false;_x000D_
 _x000D_
 this.frameRate = function(newfps) {_x000D_
  if (!arguments.length) return fps;_x000D_
  fps = newfps;_x000D_
  delay = 1000 / fps;_x000D_
  frame = -1;_x000D_
  time = null;_x000D_
 };_x000D_
 _x000D_
 this.start = function() {_x000D_
  if (!this.isPlaying) {_x000D_
   this.isPlaying = true;_x000D_
   tref = requestAnimationFrame(loop);_x000D_
  }_x000D_
 };_x000D_
 _x000D_
 this.pause = function() {_x000D_
  if (this.isPlaying) {_x000D_
   cancelAnimationFrame(tref);_x000D_
   this.isPlaying = false;_x000D_
   time = null;_x000D_
   frame = -1;_x000D_
  }_x000D_
 };_x000D_
}
_x000D_
body {font:16px sans-serif}
_x000D_
<label>Framerate: <select id=sFPS>_x000D_
 <option>12</option>_x000D_
 <option>15</option>_x000D_
 <option>24</option>_x000D_
 <option>25</option>_x000D_
 <option>29.97</option>_x000D_
 <option>30</option>_x000D_
 <option>60</option>_x000D_
</select></label><br>_x000D_
<canvas id=c height=60></canvas><br>_x000D_
<button id=bState>Start/Stop</button>
_x000D_
_x000D_
_x000D_

Old answer

The main purpose of requestAnimationFrame is to sync updates to the monitor's refresh rate. This will require you to animate at the FPS of the monitor or a factor of it (ie. 60, 30, 15 FPS for a typical refresh rate @ 60 Hz).

If you want a more arbitrary FPS then there is no point using rAF as the frame rate will never match the monitor's update frequency anyways (just a frame here and there) which simply cannot give you a smooth animation (as with all frame re-timings) and you can might as well use setTimeout or setInterval instead.

This is also a well known problem in the professional video industry when you want to playback a video at a different FPS then the device showing it refresh at. Many techniques has been used such as frame blending and complex re-timing re-building intermediate frames based on motion vectors, but with canvas these techniques are not available and the result will always be jerky video.

var FPS = 24;  /// "silver screen"
var isPlaying = true;

function loop() {
    if (isPlaying) setTimeout(loop, 1000 / FPS);

    ... code for frame here
}

The reason why we place setTimeout first (and why some place rAF first when a poly-fill is used) is that this will be more accurate as the setTimeout will queue an event immediately when the loop starts so that no matter how much time the remaining code will use (provided it doesn't exceed the timeout interval) the next call will be at the interval it represents (for pure rAF this is not essential as rAF will try to jump onto the next frame in any case).

Also worth to note that placing it first will also risk calls stacking up as with setInterval. setInterval may be slightly more accurate for this use.

And you can use setInterval instead outside the loop to do the same.

var FPS = 29.97;   /// NTSC
var rememberMe = setInterval(loop, 1000 / FPS);

function loop() {

    ... code for frame here
}

And to stop the loop:

clearInterval(rememberMe);

In order to reduce frame rate when the tab gets blurred you can add a factor like this:

var isFocus = 1;
var FPS = 25;

function loop() {
    setTimeout(loop, 1000 / (isFocus * FPS)); /// note the change here

    ... code for frame here
}

window.onblur = function() {
    isFocus = 0.5; /// reduce FPS to half   
}

window.onfocus = function() {
    isFocus = 1; /// full FPS
}

This way you can reduce the FPS to 1/4 etc.

How to break a while loop from an if condition inside the while loop?

An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".

If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.

justify-content property isn't working

justify-content only has an effect if there's space left over after your flex items have flexed to absorb the free space. In most/many cases, there won't be any free space left, and indeed justify-content will do nothing.

Some examples where it would have an effect:

  • if your flex items are all inflexible (flex: none or flex: 0 0 auto), and smaller than the container.

  • if your flex items are flexible, BUT can't grow to absorb all the free space, due to a max-width on each of the flexible items.

In both of those cases, justify-content would be in charge of distributing the excess space.

In your example, though, you have flex items that have flex: 1 or flex: 6 with no max-width limitation. Your flexible items will grow to absorb all of the free space, and there will be no space left for justify-content to do anything with.

HTML: How to make a submit button with text + image in it?

Please refer to this link. You can have any button you want just use javascript to submit the form

http://www.w3schools.com/jsref/met_form_submit.asp

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

How to add "active" class to Html.ActionLink in ASP.NET MVC

May be little late. But hope this helps.

public static class Utilities
{
    public static string IsActive(this HtmlHelper html, 
                                  string control,
                                  string action)
    {
        var routeData = html.ViewContext.RouteData;

        var routeAction = (string)routeData.Values["action"];
        var routeControl = (string)routeData.Values["controller"];

        // both must match
        var returnActive = control == routeControl &&
                           action == routeAction;

        return returnActive ? "active" : "";
    }
}

And usage as follow:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li class='@Html.IsActive("Home", "Index")'>
            @Html.ActionLink("Home", "Index", "Home")
        </li>
        <li class='@Html.IsActive("Home", "About")'>
            @Html.ActionLink("About", "About", "Home")
        </li>
        <li class='@Html.IsActive("Home", "Contact")'>
            @Html.ActionLink("Contact", "Contact", "Home")
        </li>
    </ul>
</div>

Got reference from http://www.codingeverything.com/2014/05/mvcbootstrapactivenavbar.html

How do I check for vowels in JavaScript?

I kind of like this method which I think covers all the bases:

const matches = str.match(/aeiou/gi];
return matches ? matches.length : 0;

Can not connect to local PostgreSQL

I had this problem plaguing me, and upon further investigation (running rake db:setup), I saw that rails was trying to connect to a previously used postgres instance - one which was stored in env variables as DATABASE_URL.

The fix: unset DATABASE_URL

source: https://stackoverflow.com/a/17420624/2577622

How to wait till the response comes from the $http request, in angularjs?

for people new to this you can also use a callback for example:

In your service:

.factory('DataHandler',function ($http){

   var GetRandomArtists = function(data, callback){
     $http.post(URL, data).success(function (response) {
         callback(response);
      });
   } 
})

In your controller:

    DataHandler.GetRandomArtists(3, function(response){
      $scope.data.random_artists = response;
   });

Deleting an object in C++

Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete will call the object's destructor, just like new has to invoke the constructor.

If you weren't instantiating Object1 directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?

BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto, as is the default) variable of said function!

Run text file as commands in Bash

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

Dilemma: when to use Fragments vs Activities:

Why I prefer Fragment over Activity in ALL CASES.

  • Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack, its views will be destroyed. So you can stack much more Fragments than Activity.

  • Backstack manipulation. With FragmentManager, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.

  • A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments() to find specific Fragment (not encouraged).

Difference between <input type='button' /> and <input type='submit' />

<input type="button"> can be used anywhere, not just within form and they do not submit form if they are in one. Much better suited with Javascript.

<input type="submit"> should be used in forms only and they will send a request (either GET or POST) to specified URL. They should not be put in any HTML place.

How to parse XML using shellscript?

Here's a full working example.
If it's only extracting email addresses you could just do something like:
1) Suppose XML file spam.xml is like

<spam>
<victims>
  <victim>
    <name>The Pope</name>
    <email>[email protected]</email>
    <is_satan>0</is_satan>
  </victim>
  <victim>
    <name>George Bush</name>
    <email>[email protected]</email>
    <is_satan>1</is_satan>
  </victim>
  <victim>
    <name>George Bush Jr</name>
    <email>[email protected]</email>
    <is_satan>0</is_satan>
  </victim>
</victims>
</spam>

2) You can get the emails and process them with this short bash code:

#!/bin/bash
emails=($(grep -oP '(?<=email>)[^<]+' "/my_path/spam.xml"))

for i in ${!emails[*]}
do
  echo "$i" "${emails[$i]}"
  # instead of echo use the values to send emails, etc
done

Result of this example is:

0 [email protected]
1 [email protected]
2 [email protected]

Important note:
Don't use this for serious matters. This is OK for playing around, getting quick results, learning grep, etc. but you should definitely look for, learn and use an XML parser for production (see Micha's comment below).

jQuery: Count number of list elements?

try

$("#mylist").children().length

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This error occurs because the transaction log becomes full due to LOG_BACKUP. Therefore, you can’t perform any action on this database, and In this case, the SQL Server Database Engine will raise a 9002 error.

To solve this issue you should do the following

  • Take a Full database backup.
  • Shrink the log file to reduce the physical file size.
  • Create a LOG_BACKUP.
  • Create a LOG_BACKUP Maintenance Plan to take backup logs frequently.

I wrote an article with all details regarding this error and how to solve it at The transaction log for database ‘SharePoint_Config’ is full due to LOG_BACKUP

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

Visual Studio replace tab with 4 spaces?

None of these answer were working for me on my macbook pro. So what i had to do was go to:

Preferences -> Source Code -> Code Formatting -> C# source code.

From here I could change my style and spacing tabs etc. This is the only project i have where the lead developer has different formatting than i do. It was a pain in the butt that my IDE would format my code different than theirs.

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

My problem was resolved after cleaning up some directories and files left over from the previous versions of the tools. ADT Rev 14 changes where binaries are stored. I deleted the entire bin directory, restarted Eclipse and cleaned the build and forced a rebuild. That seemed to do the trick initially but the problem came back after the next run.

I finally discovered that my bin directory was included in the project build path. I excluded bin from the build path and repeated the steps above. This resolved my problem.

Git commit in terminal opens VIM, but can't get back to terminal

Simply doing the vim "save and quit" command :wq should do the trick.

In order to have Git open it in another editor, you need to change the Git core.editor setting to a command which runs the editor you want.

git config --global core.editor "command to start sublime text 2"

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

How to validate a url in Python? (Malformed or not)

I landed on this page trying to figure out a sane way to validate strings as "valid" urls. I share here my solution using python3. No extra libraries required.

See https://docs.python.org/2/library/urlparse.html if you are using python2.

See https://docs.python.org/3.0/library/urllib.parse.html if you are using python3 as I am.

import urllib
from pprint import pprint

invalid_url = 'dkakasdkjdjakdjadjfalskdjfalk'
valid_url = 'https://stackoverflow.com'
tokens = [urllib.parse.urlparse(url) for url in (invalid_url, valid_url)]

for token in tokens:
    pprint(token)

min_attributes = ('scheme', 'netloc')  # add attrs to your liking
for token in tokens:
    if not all([getattr(token, attr) for attr in min_attributes]):
        error = "'{url}' string has no scheme or netloc.".format(url=token.geturl())
        print(error)
    else:
        print("'{url}' is probably a valid url.".format(url=token.geturl()))

ParseResult(scheme='', netloc='', path='dkakasdkjdjakdjadjfalskdjfalk', params='', query='', fragment='')

ParseResult(scheme='https', netloc='stackoverflow.com', path='', params='', query='', fragment='')

'dkakasdkjdjakdjadjfalskdjfalk' string has no scheme or netloc.

'https://stackoverflow.com' is probably a valid url.

Here is a more concise function:

from urllib.parse import urlparse

min_attributes = ('scheme', 'netloc')


def is_valid(url, qualifying=min_attributes):
    tokens = urlparse(url)
    return all([getattr(tokens, qualifying_attr)
                for qualifying_attr in qualifying])

Why is document.write considered a "bad practice"?

Browser Violation

.write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process. Only at this time will the parser resume.

Performance

The biggest consequence of employing such a method is lowered performance. The browser will take longer to load page content. The adverse reaction on load time depends on what is being written to the document. You won't see much of a difference if you are adding a <p> tag to the DOM as opposed to passing an array of 50-some references to JavaScript libraries (something which I have seen in working code and resulted in an 11 second delay - of course, this also depends on your hardware).

All in all, it's best to steer clear of this method if you can help it.

For more info see Intervening against document.write()

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

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

Just use indexing

df.iloc[:-1,:]

That's why iloc exists. You can also use head or tail.

Get refresh token google api

This is complete code in PHP using google official SDK

$client = new Google_Client();
## some need parameter
$client->setApplicationName('your application name');
$client->setClientId('****************');
$client->setClientSecret('************');
$client->setRedirectUri('http://your.website.tld/complete/url2redirect');
$client->setScopes('https://www.googleapis.com/auth/userinfo.email');
## these two lines is important to get refresh token from google api
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); # this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access

How can I override Bootstrap CSS styles?

Give ID to legend and apply css. Like add id hello to legend() the css is as follw:

#legend  legend {
  display: block;
  width: 100%;
  padding: 0;
  margin-bottom: 20px;
  font-size: 21px;
  line-height: inherit;
  color: #333333;
  border: 0;
  border-bottom: 1px solid #e5e5e5;
}

Swing vs JavaFx for desktop applications

I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul.

Also, SWT is actually newer and more actively maintained than Swing. (It was originally developed as a replacement for Swing using native components).

Regex to get the words after matching string

You're almost there. Use the following regex (with multi-line option enabled)

\bObject Name:\s+(.*)$

The complete match would be

Object Name:   D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

while the captured group one would contain

D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log

If you want to capture the file path directly use

(?m)(?<=\bObject Name:).*$

What is tail call optimization?

Note first of all that not all languages support it.

TCO applys to a special case of recursion. The gist of it is, if the last thing you do in a function is call itself (e.g. it is calling itself from the "tail" position), this can be optimized by the compiler to act like iteration instead of standard recursion.

You see, normally during recursion, the runtime needs to keep track of all the recursive calls, so that when one returns it can resume at the previous call and so on. (Try manually writing out the result of a recursive call to get a visual idea of how this works.) Keeping track of all the calls takes up space, which gets significant when the function calls itself a lot. But with TCO, it can just say "go back to the beginning, only this time change the parameter values to these new ones." It can do that because nothing after the recursive call refers to those values.

Response.Redirect with POST instead of Get?

I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.

Functions are not valid as a React child. This may happen if you return a Component instead of from render

it also happens when you call a function from jsx directly rather than in an event. like

it will show the error if you write like

<h1>{this.myFunc}<h2>

it will go if you write:

<h1 onClick={this.myFunc}>Hit Me</h1>

Access Https Rest Service using Spring RestTemplate

Here is some code that will give you the general idea.

You need to create a custom ClientHttpRequestFactory in order to trust the certificate. It looks like this:

final ClientHttpRequestFactory clientHttpRequestFactory =
        new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
    restTemplate.setRequestFactory(clientHttpRequestFactory);

This is the implementation for MyCustomClientHttpRequestFactory:

public class MyCustomClientHttpRequestFactory  extends SimpleClientHttpRequestFactory {

private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;

public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
    final ServerInfo serverInfo) {
    this.hostNameVerifier = hostNameVerifier;
    this.serverInfo = serverInfo;
}

@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
    throws IOException {
    if (connection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
        ((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
            .getSocketFactory());
    }
    super.prepareConnection(connection, httpMethod);
}

private SSLContext initSSLContext() {
    try {
        System.setProperty("https.protocols", "TLSv1");

        // Set ssl trust manager. Verify against our server thumbprint
        final SSLContext ctx = SSLContext.getInstance("TLSv1");
        final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
        final ThumbprintTrustManager thumbPrintTrustManager =
            new ThumbprintTrustManager(null, verifier);
        ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
        return ctx;
    } catch (final Exception ex) {
        LOGGER.error(
            "An exception was thrown while trying to initialize HTTP security manager.", ex);
        return null;
    }
}

In this case my serverInfo object contains the thumbprint of the server. You need to implement the TrustManager interface to get the SslThumbprintVerifier or any other method you want to verify your certificate (you can also decide to also always return true).

The value org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER allows all host names. If you need to verify the host name, you will need to implement it differently.

I'm not sure about the user and password and how you implemented it. Often, you need to add a header to the restTemplate named Authorization with a value that looks like this: Base: <encoded user+password>. The user+password must be Base64 encoded.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

Git fatal: protocol 'https' is not supported

Problem

git clone https://github.com/rojarfast1991/TestGit.git fatal: protocol 'https' is not supported

Solution:

Steps:

(1):- Open the new terminal and clone the git repository

git clone https://github.com/rojarfast1991/TestGit.git

(2) Automatic git login prompt will open and it will be asked you to enter a user credential.

UserName : - xxxxxxx

PassWord : - xxxxxxx

Finally, cloning will start...

git clone https://github.com/rojarfast1991/TestGit.git
Cloning into 'TestGit'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), done.

How to read fetch(PDO::FETCH_ASSOC);

Loop through the array like any other Associative Array:

while($data = $datas->fetch( PDO::FETCH_ASSOC )){ 
     print $data['title'].'<br>'; 
}

or

$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);

echo '<pre>'.$resultset.'</pre>';

PHP: Possible to automatically get all POSTed data?

Yes you can use simply

     $input_data = $_POST;

or extract() may be useful for you.

Capturing "Delete" Keypress with jQuery

$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

Source: javascript char codes key codes from www.cambiaresearch.com

How to make asynchronous HTTP requests in PHP

If you control the target that you want to call asynchronously (e.g. your own "longtask.php"), you can close the connection from that end, and both scripts will run in parallel. It works like this:

  1. quick.php opens longtask.php via cURL (no magic here)
  2. longtask.php closes the connection and continues (magic!)
  3. cURL returns to quick.php when the connection is closed
  4. Both tasks continue in parallel

I have tried this, and it works just fine. But quick.php won't know anything about how longtask.php is doing, unless you create some means of communication between the processes.

Try this code in longtask.php, before you do anything else. It will close the connection, but still continue to run (and suppress any output):

while(ob_get_level()) ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo('Connection Closed');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();

The code is copied from the PHP manual's user contributed notes and somewhat improved.

Difference between application/x-javascript and text/javascript content types

text/javascript is obsolete, and application/x-javascript was experimental (hence the x- prefix) for a transitional period until application/javascript could be standardised.

You should use application/javascript. This is documented in the RFC.

As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/* and application/* MIME type groups had a consistent meaning where possible. (text/* MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).

Note that using application/javascript in the type attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript there or omit the attribute entirely (which is permitted in HTML 5).

This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript.

Accessing dict keys like an attribute?

What if you wanted a key which was a method, such as __eq__ or __getattr__?

And you wouldn't be able to have an entry that didn't start with a letter, so using 0343853 as a key is out.

And what if you didn't want to use a string?

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Let's start from the beginning and explore this question.

So let's suppose you have two lists:

list_1=['01','98']
list_2=[['01','98']]

And we have to copy both lists, now starting from the first list:

So first let's try by setting the variable copy to our original list, list_1:

copy=list_1

Now if you are thinking copy copied the list_1, then you are wrong. The id function can show us if two variables can point to the same object. Let's try this:

print(id(copy))
print(id(list_1))

The output is:

4329485320
4329485320

Both variables are the exact same argument. Are you surprised?

So as we know python doesn't store anything in a variable, Variables are just referencing to the object and object store the value. Here object is a list but we created two references to that same object by two different variable names. This means that both variables are pointing to the same object, just with different names.

When you do copy=list_1, it is actually doing:

enter image description here

Here in the image list_1 and copy are two variable names but the object is same for both variable which is list

So if you try to modify copied list then it will modify the original list too because the list is only one there, you will modify that list no matter you do from the copied list or from the original list:

copy[0]="modify"

print(copy)
print(list_1)

output:

['modify', '98']
['modify', '98']

So it modified the original list :

Now let's move onto a pythonic method for copying lists.

copy_1=list_1[:]

This method fixes the first issue we had:

print(id(copy_1))
print(id(list_1))

4338792136
4338791432

So as we can see our both list having different id and it means that both variables are pointing to different objects. So what actually going on here is:

enter image description here

Now let's try to modify the list and let's see if we still face the previous problem:

copy_1[0]="modify"

print(list_1)
print(copy_1)

The output is:

['01', '98']
['modify', '98']

As you can see, it only modified the copied list. That means it worked.

Do you think we're done? No. Let's try to copy our nested list.

copy_2=list_2[:]

list_2 should reference to another object which is copy of list_2. Let's check:

print(id((list_2)),id(copy_2))

We get the output:

4330403592 4330403528

Now we can assume both lists are pointing different object, so now let's try to modify it and let's see it is giving what we want:

copy_2[0][1]="modify"

print(list_2,copy_2)

This gives us the output:

[['01', 'modify']] [['01', 'modify']]

This may seem a little bit confusing, because the same method we previously used worked. Let's try to understand this.

When you do:

copy_2=list_2[:]

You're only copying the outer list, not the inside list. We can use the id function once again to check this.

print(id(copy_2[0]))
print(id(list_2[0]))

The output is:

4329485832
4329485832

When we do copy_2=list_2[:], this happens:

enter image description here

It creates the copy of list but only outer list copy, not the nested list copy, nested list is same for both variable, so if you try to modify the nested list then it will modify the original list too as the nested list object is same for both lists.

What is the solution? The solution is the deepcopy function.

from copy import deepcopy
deep=deepcopy(list_2)

Let's check this:

print(id((list_2)),id(deep))

4322146056 4322148040

Both outer lists have different IDs, let's try this on the inner nested lists.

print(id(deep[0]))
print(id(list_2[0]))

The output is:

4322145992
4322145800

As you can see both IDs are different, meaning we can assume that both nested lists are pointing different object now.

This means when you do deep=deepcopy(list_2) what actually happens:

enter image description here

Both nested lists are pointing different object and they have separate copy of nested list now.

Now let's try to modify the nested list and see if it solved the previous issue or not:

deep[0][1]="modify"
print(list_2,deep)

It outputs:

[['01', '98']] [['01', 'modify']]

As you can see, it didn't modify the original nested list, it only modified the copied list.

Does Hibernate create tables in the database automatically

Yes, Hibernate can be configured by way of the hibernate.hbm2ddl.auto property in the hibernate.cfg.xml file to automatically create tables in your DB in order to store your entities in them if the table doesn't already exist.

This can be handy during development where a new, in-memory, DB can be used and created a new on every run of the application or during testing.

json_encode/json_decode - returns stdClass instead of Array in PHP

Although, as mentioned, you could add a second parameter here to indicate you want an array returned:

$array = json_decode($json, true);

Many people might prefer to cast the results instead:

$array = (array)json_decode($json);

It might be more clear to read.

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

How to rename with prefix/suffix?

In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:

# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream

So you can do your rename as follows:

mv {,new.}original.filename

as this expands to:

mv original.filename new.original.filename

How to change the date format of a DateTimePicker in vb.net

Try this code it works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
    MsgBox(CustomeDate.ToString)

    con.Open()

    dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)

    ds = New System.Data.DataSet
    dadap.Fill(ds)
    Dgview.DataSource = ds.Tables(0)
    con.Close()

Note : if u use dd for date representation it will return nothing while selecting 1 to 9 so use d for selection

'Date time format
'MMM     Three-letter month.
'ddd     Three-letter day of the week.
'd       Day of the month.
'HH      Two-digit hours on 24-hour scale.
'mm      Two-digit minutes.
'yyyy    Four-digit year.

The documentation contains a full list of the date formats.

Iframe transparent background

I've used this creating an IFrame through Javascript and it worked for me:

// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";

Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

By looking into SQL SERVER log file in "C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Log\ERRORLOG", it says "Login failed for user 'XXXXX'. Reason: An attempt to login using SQL authentication failed. Server is configured for Windows authentication only. [CLIENT: ]"

The fixing method is to open "Microsoft SQL Server Management Studio" -> Right click the SQL server and then select "Properties" -> Security -> Change the authentication to mixed mode. -> Restart SQL server.

How to go to a specific element on page?

The standard technique in plugin form would look something like this:

(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
})(jQuery);

Then you could just say $('#div_element2').goTo(); to scroll to <div id="div_element2">. Options handling and configurability is left as an exercise for the reader.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

How can I set the current working directory to the directory of the script in Bash?

Try the following simple one-liners:


For all UNIX/OSX/Linux

dir=$(cd -P -- "$(dirname -- "$0")" && pwd -P)

Bash

dir=$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)

Note: A double dash (--) is used in commands to signify the end of command options, so files containing dashes or other special characters won't break the command.

Note: In Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).


For Linux, Mac and other *BSD:

cd "$(dirname "$(realpath "$0")")";

Note: realpath should be installed in the most popular Linux distribution by default (like Ubuntu), but in some it can be missing, so you have to install it.

Note: If you're using Bash, use ${BASH_SOURCE[0]} in favor of $0, otherwise the path can break when sourcing it (source/.).

Otherwise you could try something like that (it will use the first existing tool):

cd "$(dirname "$(readlink -f "$0" || realpath "$0")")"

For Linux specific:

cd "$(dirname "$(readlink -f "$0")")"

Using GNU readlink on *BSD/Mac:

cd "$(dirname "$(greadlink -f "$0")")"

Note: You need to have coreutils installed (e.g. 1. Install Homebrew, 2. brew install coreutils).


In bash

In bash you can use Parameter Expansions to achieve that, like:

cd "${0%/*}"

but it doesn't work if the script is run from the same directory.

Alternatively you can define the following function in bash:

realpath () {
  [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
}

This function takes 1 argument. If argument has already absolute path, print it as it is, otherwise print $PWD variable + filename argument (without ./ prefix).

or here is the version taken from Debian .bashrc file:

function realpath()
{
    f=$@
    if [ -d "$f" ]; then
        base=""
        dir="$f"
    else
        base="/$(basename "$f")"
        dir=$(dirname "$f")
    fi
    dir=$(cd "$dir" && /bin/pwd)
    echo "$dir$base"
}

Related:

See also:

How can I get the behavior of GNU's readlink -f on a Mac?

Converting year and month ("yyyy-mm" format) to a date?

Using anytime package:

library(anytime)

anydate("2009-01")
# [1] "2009-01-01"

Hive: how to show all partitions of a table?

CLI has some limit when ouput is displayed. I suggest to export output into local file:

$hive -e 'show partitions table;' > partitions

Calculate difference between two dates (number of days)?

For a and b as two DateTime types:

DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();

Databinding an enum property to a ComboBox in WPF

Use ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

and then bind to static resource:

ItemsSource="{Binding Source={StaticResource enumValues}}"

Find this solution at this blog

Reason to Pass a Pointer by Reference in C++?

One example is when you write a parser function and pass it a source pointer to read from, if the function is supposed to push that pointer forward behind the last character which has been correctly recognized by the parser. Using a reference to a pointer makes it clear then that the function will move the original pointer to update its position.

In general, you use references to pointers if you want to pass a pointer to a function and let it move that original pointer to some other position instead of just moving a copy of it without affecting the original.

Changing the background color of a drop down list transparent in html

You can actualy fake the transparency of option DOMElements with the following CSS:

CSS

option { 
    /* Whatever color  you want */
    background-color: #82caff;
}

See Demo

The option tag does not support rgba colors yet.

How do I get the last day of a month?

I don't know C# but, if it turns out there's not a convenient API way to get it, one of the ways you can do so is by following the logic:

today -> +1 month -> set day of month to 1 -> -1 day

Of course, that assumes you have date math of that type.

Issue with adding common code as git submodule: "already exists in the index"

This happens if the .git file is missing in the target path. It happend to me after I executed git clean -f -d.

I had to delete all target folders showing in the message and then executing git submodule update --remote

How to make a .NET Windows Service start right after the installation?

The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

How to put scroll bar only for modal-body?

A simple js solution to set modal height proportional to body's height :

$(document).ready(function () {
    $('head').append('<style type="text/css">.modal .modal-body {max-height: ' + ($('body').height() * .8) + 'px;overflow-y: auto;}.modal-open .modal{overflow-y: hidden !important;}</style>');
});

body's height has to be 100% :

html, body {
    height: 100%;
    min-height: 100%;
}

I set modal body height to 80% of body, this can be of course customized.

Hope it helps.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

How to move up a directory with Terminal in OS X

For Mac Terminal

cd ..   # one up
cd ../  # two up
cd      # home directory 
cd /    # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces

NSDictionary to NSArray?

There are a few things that could be happening here.

Is the dictionary you have listed the myDict? If so, then you don't have an object with a key of @"items", and the dict variable will be nil. You need to iterate through myDict directly.

Another thing to check is if _myArray is a valid instance of an NSMutableArray. If it's nil, the addObject: method will silently fail.

And a final thing to check is that the objects inside your dictionary are properly encased in NSNumbers (or some other non-primitive type).

PHP Sort a multidimensional array by element containing date

From php7 you can use the Spaceship operator:

usort($array, function($a, $b) {
  return new DateTime($a['datetime']) <=> new DateTime($b['datetime']);
});

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

iPhone Debugging: How to resolve 'failed to get the task for process'?

I Had the same issue, but resolved it by following simple following steps :

  1. Make sure you have selected debug rather than release.
  2. In Debug configurations, in project settings, you should have selected developer's profile & no need of specifying the entitlements plist.
  3. Also same setting are there under: Targets: , if not manuall change them to the above for the debug config. It will work.

All the best.

How can I change the language (to english) in Oracle SQL Developer?

With SQL Developer 4.x, the language option is to be added to ..\sqldeveloper\bin\sqldeveloper.conf, rather than ..\sqldeveloper\bin\ide.conf:

# ----- MODIFICATION BEGIN -----
AddVMOption -Duser.language=en
# ----- MODIFICATION END -----

How can I hide the Android keyboard using JavaScript?

For anyone using vuejs or jquery with cordova, use document.activeElement.blur() ;

hideKeyboard() {
    document.activeElement.blur();
}

..and from my text box, I just call that function:

For VueJS : v-on:keyup.enter="hideKeyboard" Pressing the enter button closes the android keyboard.

for jQuery:

$('element').keypress(function(e) {
  if(e.keyCode===13) document.activeElement.blur();
}

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

The best place to demystify this is the source code. The docs are woefully inadequate about explaining this.

dispatchTouchEvent is actually defined on Activity, View and ViewGroup. Think of it as a controller which decides how to route the touch events.

For example, the simplest case is that of View.dispatchTouchEvent which will route the touch event to either OnTouchListener.onTouch if it's defined or to the extension method onTouchEvent.

For ViewGroup.dispatchTouchEvent things are way more complicated. It needs to figure out which one of its child views should get the event (by calling child.dispatchTouchEvent). This is basically a hit testing algorithm where you figure out which child view's bounding rectangle contains the touch point coordinates.

But before it can dispatch the event to the appropriate child view, the parent can spy and/or intercept the event all together. This is what onInterceptTouchEvent is there for. So it calls this method first before doing the hit testing and if the event was hijacked (by returning true from onInterceptTouchEvent) it sends a ACTION_CANCEL to the child views so they can abandon their touch event processing (from previous touch events) and from then onwards all touch events at the parent level are dispatched to onTouchListener.onTouch (if defined) or onTouchEvent(). Also in that case, onInterceptTouchEvent is never called again.

Would you even want to override [Activity|ViewGroup|View].dispatchTouchEvent? Unless you are doing some custom routing you probably should not.

The main extension methods are ViewGroup.onInterceptTouchEvent if you want to spy and/or intercept touch event at the parent level and View.onTouchListener/View.onTouchEvent for main event handling.

All in all its overly complicated design imo but android apis lean more towards flexibility than simplicity.

HttpClient.GetAsync(...) never returns when using await/async

You are misusing the API.

Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).

This is managed by the ASP.NET SynchronizationContext.

By default, when you await a Task, the method resumes on a captured SynchronizationContext (or a captured TaskScheduler, if there is no SynchronizationContext). Normally, this is just what you want: an asynchronous controller action will await something, and when it resumes, it resumes with the request context.

So, here's why test5 fails:

  • Test5Controller.Get executes AsyncAwait_GetSomeDataAsync (within the ASP.NET request context).
  • AsyncAwait_GetSomeDataAsync executes HttpClient.GetAsync (within the ASP.NET request context).
  • The HTTP request is sent out, and HttpClient.GetAsync returns an uncompleted Task.
  • AsyncAwait_GetSomeDataAsync awaits the Task; since it is not complete, AsyncAwait_GetSomeDataAsync returns an uncompleted Task.
  • Test5Controller.Get blocks the current thread until that Task completes.
  • The HTTP response comes in, and the Task returned by HttpClient.GetAsync is completed.
  • AsyncAwait_GetSomeDataAsync attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get.
  • Deadlock.

Here's why the other ones work:

  • (test1, test2, and test3): Continuations_GetSomeDataAsync schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task returned by Continuations_GetSomeDataAsync to complete without having to re-enter the request context.
  • (test4 and test6): Since the Task is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync to use the ASP.NET request context when it is ready to continue.

And here's the best practices:

  1. In your "library" async methods, use ConfigureAwait(false) whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  2. Don't block on Tasks; it's async all the way down. In other words, use await instead of GetResult (Task.Result and Task.Wait should also be replaced with await).

That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async (which doesn't block a request thread).

More information:

Update 2012-07-13: Incorporated this answer into a blog post.

How to clear the cache in NetBeans

tl;dr You might not need to whack your entire NetBeans cache.


My problem manifested as running a clean build didn't delete the previous build folder or testuserdir folder, while I was using NetBeans 8.0.2.

The first time I had this problem, Ray Slater's answer above helped me immensely. I had two Project Groups, and had to close each project in both groups, close NetBeans, clear the cache, then add my projects back to my groups before it would work again.

Later, this problem cropped up again with NetBeans 8.1. I closed NetBeans, and ran ant build clean at the command line, and it worked. When I reopened NetBeans, the problem was resolved. It occurs to me that NetBeans was keeping something open and just needed to be closed in order to delete the folders.


Update
I finally figured out what was going on. Somehow, my NetBeans "Module Suite Project" (yellow/orange puzzle pieces icon) had been closed and the "Module Project" (purple puzzle piece icon) having the same exact name as the "Module Suite Project" was open. Building clean cleaned that particular Project correctly, but did not clean the entire Suite.

Now that I have the "Module Suite Project" opened correctly again, things work as expected. This explains why ant build clean worked, since it was done on the command line at the right level to clean the whole Suite.

I suspect I didn't strictly need to clean out my NetBeans cache at all though perhaps doing so actually fixed the issue of why it was only showing the "Module Project" instead of the "Module Suite Project", thereby doing the right thing when I clicked build clean... If I had simply realized that the Suite was no longer open and only the Project was, I could have fixed it in three seconds.

Object of class mysqli_result could not be converted to string in

mysqli:query() returns a mysqli_result object, which cannot be serialized into a string.

You need to fetch the results from the object. Here's how to do it.

If you need a single value.

Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

If you need multiple values.

Use foreach loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];
}

How to declare or mark a Java method as deprecated?

Take a look at the @Deprecated annotation.

Programmatically create a UIView with color gradient

I have implemented this in my code.

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 31.0f)];
view1.backgroundColor = [UIColor clearColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view1.bounds;
UIColor *topColor = [UIColor colorWithRed:132.0/255.0 green:222.0/255.0 blue:109.0/255.0 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:31.0/255.0 green:150.0/255.0 blue:99.0/255.0 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];


[view1.layer insertSublayer:gradient atIndex:0];

Now I can see a gradient on my view.

How to install Android app on LG smart TV?

Here is a great guide how to do that, if your TV is android TV: https://pedronveloso.com/how-to-install-an-apk-on-android-tv/

Have you enabled 'unknown sources' from security and restrictions settings?

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

Lumen: get URL parameter in a Blade view

if you use route and pass paramater use this code in your blade file

{{dd(request()->route()->parameters)}}

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

How to remove all white space from the beginning or end of a string?

String.Trim() removes all whitespace from the beginning and end of a string. To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

I landed here because I was looking for something like that too. In my case, I was copying the data from a set of staging tables with many columns into one table while also assigning row ids to the target table. Here is a variant of the above approaches that I used. I added the serial column at the end of my target table. That way I don't have to have a placeholder for it in the Insert statement. Then a simple select * into the target table auto populated this column. Here are the two SQL statements that I used on PostgreSQL 9.6.4.

ALTER TABLE target ADD COLUMN some_column SERIAL;
INSERT INTO target SELECT * from source;

How to Compare a long value is equal to Long value

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b.longValue())
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

or:

    public static void main(String[] args) {
        long a = 1111;
        Long b = 1113L;
        if(a == b)
    {
        System.out.println("Equals");
    }else{
        System.out.println("not equals");
    }
  }

Differences between action and actionListener

actionListener

Use actionListener if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>), and/or to have access to the component which invoked the action (which is available by ActionEvent argument). So, purely for preparing purposes before the real business action gets invoked.

The actionListener method has by default the following signature:

import javax.faces.event.ActionEvent;
// ...

public void actionListener(ActionEvent event) {
    // ...
}

And it's supposed to be declared as follows, without any method parentheses:

<h:commandXxx ... actionListener="#{bean.actionListener}" />

Note that you can't pass additional arguments by EL 2.2. You can however override the ActionEvent argument altogether by passing and specifying custom argument(s). The following examples are valid:

<h:commandXxx ... actionListener="#{bean.methodWithoutArguments()}" />
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
public void methodWithoutArguments() {}
public void methodWithOneArgument(Object arg1) {}
public void methodWithTwoArguments(Object arg1, Object arg2) {}

Note the importance of the parentheses in the argumentless method expression. If they were absent, JSF would still expect a method with ActionEvent argument.

If you're on EL 2.2+, then you can declare multiple action listener methods via <f:actionListener binding>.

<h:commandXxx ... actionListener="#{bean.actionListener1}">
    <f:actionListener binding="#{bean.actionListener2()}" />
    <f:actionListener binding="#{bean.actionListener3()}" />
</h:commandXxx>
public void actionListener1(ActionEvent event) {}
public void actionListener2() {}
public void actionListener3() {}

Note the importance of the parentheses in the binding attribute. If they were absent, EL would confusingly throw a javax.el.PropertyNotFoundException: Property 'actionListener1' not found on type com.example.Bean, because the binding attribute is by default interpreted as a value expression, not as a method expression. Adding EL 2.2+ style parentheses transparently turns a value expression into a method expression. See also a.o. Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?


action

Use action if you want to execute a business action and if necessary handle navigation. The action method can (thus, not must) return a String which will be used as navigation case outcome (the target view). A return value of null or void will let it return to the same page and keep the current view scope alive. A return value of an empty string or the same view ID will also return to the same page, but recreate the view scope and thus destroy any currently active view scoped beans and, if applicable, recreate them.

The action method can be any valid MethodExpression, also the ones which uses EL 2.2 arguments such as below:

<h:commandXxx value="submit" action="#{bean.edit(item)}" />

With this method:

public void edit(Item item) {
    // ...
}

Note that when your action method solely returns a string, then you can also just specify exactly that string in the action attribute. Thus, this is totally clumsy:

<h:commandLink value="Go to next page" action="#{bean.goToNextpage}" />

With this senseless method returning a hardcoded string:

public String goToNextpage() {
    return "nextpage";
}

Instead, just put that hardcoded string directly in the attribute:

<h:commandLink value="Go to next page" action="nextpage" />

Please note that this in turn indicates a bad design: navigating by POST. This is not user nor SEO friendly. This all is explained in When should I use h:outputLink instead of h:commandLink? and is supposed to be solved as

<h:link value="Go to next page" outcome="nextpage" />

See also How to navigate in JSF? How to make URL reflect current page (and not previous one).


f:ajax listener

Since JSF 2.x there's a third way, the <f:ajax listener>.

<h:commandXxx ...>
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandXxx>

The ajaxListener method has by default the following signature:

import javax.faces.event.AjaxBehaviorEvent;
// ...

public void ajaxListener(AjaxBehaviorEvent event) {
    // ...
}

In Mojarra, the AjaxBehaviorEvent argument is optional, below works as good.

public void ajaxListener() {
    // ...
}

But in MyFaces, it would throw a MethodNotFoundException. Below works in both JSF implementations when you want to omit the argument.

<h:commandXxx ...>
    <f:ajax execute="@form" listener="#{bean.ajaxListener()}" render="@form" />
</h:commandXxx>

Ajax listeners are not really useful on command components. They are more useful on input and select components <h:inputXxx>/<h:selectXxx>. In command components, just stick to action and/or actionListener for clarity and better self-documenting code. Moreover, like actionListener, the f:ajax listener does not support returning a navigation outcome.

<h:commandXxx ... action="#{bean.action}">
    <f:ajax execute="@form" render="@form" />
</h:commandXxx>

For explanation on execute and render attributes, head to Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.


Invocation order

The actionListeners are always invoked before the action in the same order as they are been declared in the view and attached to the component. The f:ajax listener is always invoked before any action listener. So, the following example:

<h:commandButton value="submit" actionListener="#{bean.actionListener}" action="#{bean.action}">
    <f:actionListener type="com.example.ActionListenerType" />
    <f:actionListener binding="#{bean.actionListenerBinding()}" />
    <f:setPropertyActionListener target="#{bean.property}" value="some" />
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandButton>

Will invoke the methods in the following order:

  1. Bean#ajaxListener()
  2. Bean#actionListener()
  3. ActionListenerType#processAction()
  4. Bean#actionListenerBinding()
  5. Bean#setProperty()
  6. Bean#action()

Exception handling

The actionListener supports a special exception: AbortProcessingException. If this exception is thrown from an actionListener method, then JSF will skip any remaining action listeners and the action method and proceed to render response directly. You won't see an error/exception page, JSF will however log it. This will also implicitly be done whenever any other exception is being thrown from an actionListener. So, if you intend to block the page by an error page as result of a business exception, then you should definitely be performing the job in the action method.

If the sole reason to use an actionListener is to have a void method returning to the same page, then that's a bad one. The action methods can perfectly also return void, on the contrary to what some IDEs let you believe via EL validation. Note that the PrimeFaces showcase examples are littered with this kind of actionListeners over all place. This is indeed wrong. Don't use this as an excuse to also do that yourself.

In ajax requests, however, a special exception handler is needed. This is regardless of whether you use listener attribute of <f:ajax> or not. For explanation and an example, head to Exception handling in JSF ajax requests.

regex to remove all text before a character

In Javascript I would use /.*_/, meaning: match everything until _ (including)

Example:

console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

How to check if a variable is equal to one string or another string?

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False

Trying to Validate URL Using JavaScript

My solution:

function isValidUrl(t)
{
    return t.match(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i)
}

how do you filter pandas dataframes by multiple columns

You can create your own filter function using query in pandas. Here you have filtering of df results by all the kwargs parameters. Dont' forgot to add some validators(kwargs filtering) to get filter function for your own df.

def filter(df, **kwargs):
    query_list = []
    for key in kwargs.keys():
        query_list.append(f'{key}=="{kwargs[key]}"')
    query = ' & '.join(query_list)
    return df.query(query)

Render HTML string as real HTML in a React component

If you have control over where the string containing html is coming from (ie. somewhere in your app), you can benefit from the new <Fragment> API, doing something like:

import React, {Fragment} from 'react'

const stringsSomeWithHtml = {
  testOne: (
    <Fragment>
      Some text <strong>wrapped with strong</strong>
    </Fragment>
  ),
  testTwo: `This is just a plain string, but it'll print fine too`,
}

...

render() {
  return <div>{stringsSomeWithHtml[prop.key]}</div>
}

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

Boto3 to download all files from a S3 Bucket

I have been running into this problem for a while and with all of the different forums I've been through I haven't see a full end-to-end snip-it of what works. So, I went ahead and took all the pieces (add some stuff on my own) and have created a full end-to-end S3 Downloader!

This will not only download files automatically but if the S3 files are in subdirectories, it will create them on the local storage. In my application's instance, I need to set permissions and owners so I have added that too (can be comment out if not needed).

This has been tested and works in a Docker environment (K8) but I have added the environmental variables in the script just in case you want to test/run it locally.

I hope this helps someone out in their quest of finding S3 Download automation. I also welcome any advice, info, etc. on how this can be better optimized if needed.

#!/usr/bin/python3
import gc
import logging
import os
import signal
import sys
import time
from datetime import datetime

import boto
from boto.exception import S3ResponseError
from pythonjsonlogger import jsonlogger

formatter = jsonlogger.JsonFormatter('%(message)%(levelname)%(name)%(asctime)%(filename)%(lineno)%(funcName)')

json_handler_out = logging.StreamHandler()
json_handler_out.setFormatter(formatter)

#Manual Testing Variables If Needed
#os.environ["DOWNLOAD_LOCATION_PATH"] = "some_path"
#os.environ["BUCKET_NAME"] = "some_bucket"
#os.environ["AWS_ACCESS_KEY"] = "some_access_key"
#os.environ["AWS_SECRET_KEY"] = "some_secret"
#os.environ["LOG_LEVEL_SELECTOR"] = "DEBUG, INFO, or ERROR"

#Setting Log Level Test
logger = logging.getLogger('json')
logger.addHandler(json_handler_out)
logger_levels = {
    'ERROR' : logging.ERROR,
    'INFO' : logging.INFO,
    'DEBUG' : logging.DEBUG
}
logger_level_selector = os.environ["LOG_LEVEL_SELECTOR"]
logger.setLevel(logger_level_selector)

#Getting Date/Time
now = datetime.now()
logger.info("Current date and time : ")
logger.info(now.strftime("%Y-%m-%d %H:%M:%S"))

#Establishing S3 Variables and Download Location
download_location_path = os.environ["DOWNLOAD_LOCATION_PATH"]
bucket_name = os.environ["BUCKET_NAME"]
aws_access_key_id = os.environ["AWS_ACCESS_KEY"]
aws_access_secret_key = os.environ["AWS_SECRET_KEY"]
logger.debug("Bucket: %s" % bucket_name)
logger.debug("Key: %s" % aws_access_key_id)
logger.debug("Secret: %s" % aws_access_secret_key)
logger.debug("Download location path: %s" % download_location_path)

#Creating Download Directory
if not os.path.exists(download_location_path):
    logger.info("Making download directory")
    os.makedirs(download_location_path)

#Signal Hooks are fun
class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)
    def exit_gracefully(self, signum, frame):
        self.kill_now = True

#Downloading from S3 Bucket
def download_s3_bucket():
    conn = boto.connect_s3(aws_access_key_id, aws_access_secret_key)
    logger.debug("Connection established: ")
    bucket = conn.get_bucket(bucket_name)
    logger.debug("Bucket: %s" % str(bucket))
    bucket_list = bucket.list()
#    logger.info("Number of items to download: {0}".format(len(bucket_list)))

    for s3_item in bucket_list:
        key_string = str(s3_item.key)
        logger.debug("S3 Bucket Item to download: %s" % key_string)
        s3_path = download_location_path + "/" + key_string
        logger.debug("Downloading to: %s" % s3_path)
        local_dir = os.path.dirname(s3_path)

        if not os.path.exists(local_dir):
            logger.info("Local directory doesn't exist, creating it... %s" % local_dir)
            os.makedirs(local_dir)
            logger.info("Updating local directory permissions to %s" % local_dir)
#Comment or Uncomment Permissions based on Local Usage
            os.chmod(local_dir, 0o775)
            os.chown(local_dir, 60001, 60001)
        logger.debug("Local directory for download: %s" % local_dir)
        try:
            logger.info("Downloading File: %s" % key_string)
            s3_item.get_contents_to_filename(s3_path)
            logger.info("Successfully downloaded File: %s" % s3_path)
            #Updating Permissions
            logger.info("Updating Permissions for %s" % str(s3_path))
#Comment or Uncomment Permissions based on Local Usage
            os.chmod(s3_path, 0o664)
            os.chown(s3_path, 60001, 60001)
        except (OSError, S3ResponseError) as e:
            logger.error("Fatal error in s3_item.get_contents_to_filename", exc_info=True)
            # logger.error("Exception in file download from S3: {}".format(e))
            continue
        logger.info("Deleting %s from S3 Bucket" % str(s3_item.key))
        s3_item.delete()

def main():
    killer = GracefulKiller()
    while not killer.kill_now:
        logger.info("Checking for new files on S3 to download...")
        download_s3_bucket()
        logger.info("Done checking for new files, will check in 120s...")
        gc.collect()
        sys.stdout.flush()
        time.sleep(120)
if __name__ == '__main__':
    main()

Find all storage devices attached to a Linux machine

Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.

Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.

Case vs If Else If: Which is more efficient?

The debugger is making it simpler, because you don't want to step through the actual code that the compiler creates.

If the switch contains more than five items, it's implemented using a lookup table or hash table, otherwise it's implemeneted using an if..else.

See the closely related question is “else if” faster than “switch() case” ?.

Other languages than C# will of course implement it more or less differently, but a switch is generally more efficient.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

mongodb count num of distinct values per field/key

Here is example of using aggregation API. To complicate the case we're grouping by case-insensitive words from array property of the document.

db.articles.aggregate([
    {
        $match: {
            keywords: { $not: {$size: 0} }
        }
    },
    { $unwind: "$keywords" },
    {
        $group: {
            _id: {$toLower: '$keywords'},
            count: { $sum: 1 }
        }
    },
    {
        $match: {
            count: { $gte: 2 }
        }
    },
    { $sort : { count : -1} },
    { $limit : 100 }
]);

that give result such as

{ "_id" : "inflammation", "count" : 765 }
{ "_id" : "obesity", "count" : 641 }
{ "_id" : "epidemiology", "count" : 617 }
{ "_id" : "cancer", "count" : 604 }
{ "_id" : "breast cancer", "count" : 596 }
{ "_id" : "apoptosis", "count" : 570 }
{ "_id" : "children", "count" : 487 }
{ "_id" : "depression", "count" : 474 }
{ "_id" : "hiv", "count" : 468 }
{ "_id" : "prognosis", "count" : 428 }

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

Can you not use AcceptButton in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.

How to extract elements from a list using indices in Python?

Perhaps use this:

[a[i] for i in (1,2,5)]
# [11, 12, 15]

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

How to detect a mobile device with JavaScript?

I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
    // Take the user to a different screen here.
}

Google Chrome Full Black Screen

i have resolved this by following steps.

1) Go to customise icon in the top right corner chrome.
2) click on more tools option.
3) Click task manager.
4) Kill/end process GPU process

This has resolved my issue of black screen in chrome.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Try this:

Select user_id
from yourtable
where ancestry in ('England', 'France', 'Germany')
group by user_id
having count(user_id) = 3

The last line means the user's ancestry has all 3 countries.

Create excel ranges using column numbers in vba?

Function fncToLetters(vintCol As Integer) As String

        Dim mstrDigits As String

    ' Convert a positive number n to its digit representation in base 26.
    mstrDigits = ""
    Do While vintCol > 0
        mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
        vintCol = Int((vintCol - 1) / 26)
    Loop

    fncToLetters = mstrDigits

End Function

Removing nan values from an array

The accepted answer changes shape for 2d arrays. I present a solution here, using the Pandas dropna() functionality. It works for 1D and 2D arrays. In the 2D case you can choose weather to drop the row or column containing np.nan.

import pandas as pd
import numpy as np

def dropna(arr, *args, **kwarg):
    assert isinstance(arr, np.ndarray)
    dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
    if arr.ndim==1:
        dropped=dropped.flatten()
    return dropped

x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )


print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')

print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')

print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')

Result:

==================== 1D Case: ====================
Input:
[1400. 1500. 1600.   nan   nan   nan 1700.]

dropna:
[1400. 1500. 1600. 1700.]


==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
 [  nan    0.   nan]
 [1700. 1800.   nan]]

dropna (rows):
[[1400. 1500. 1600.]]

dropna (columns):
[[1500.]
 [   0.]
 [1800.]]


==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
 [  nan    0.   nan]
 [1700. 1800.   nan]]

dropna:
[1400. 1500. 1600. 1700.]

How to trigger a build only if changes happen on particular set of files

While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:

/*
 * Check a folder if changed in the latest commit.
 * Returns true if changed, or false if no changes.
 */
def checkFolderForDiffs(path) {
    try {
        // git diff will return 1 for changes (failure) which is caught in catch, or
        // 0 meaning no changes 
        sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
        return false
    } catch (err) {
        return true
    }
}

if ( checkFolderForDiffs('api/') ) {
    //API folder changed, run steps here
}

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Code coverage for Jest built on top of Jasmine

Try Chutzpah. I have just used it. And I blogged about it on how to integrate in Visual Studio.

This is how I did code coverage with Chutzpah: Code Coverage with Chutzpah

iPhone: Setting Navigation Bar Title

If you want to change the title of a navBar inside a tabBar controller, do this:

-(void)viewDidAppear:(BOOL)animated {
    self.navigationController.navigationBar.topItem.title = @"myTitle";
}

WPF - add static items to a combo box

Like this:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

VBA vlookup reference in different sheet

try this:

Dim ws as Worksheet

Set ws = Thisworkbook.Sheets("Sheet2")

With ws
    .Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With

End Sub

This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").

If you want to stick with your logic, declare the variables.
See below for example.

Sub Test()

Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String

Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")

With ws2
    On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
    MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
    On Error GoTo 0
    If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With

End Sub

Hope this get's you started.

Change content of div - jQuery

You could subscribe for the .click event for the links and change the contents of the div using the .html method:

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').html(linkText);

    // cancel the default action of the link by returning false
    return false;
});

Note however that if you replace the contents of this div the click handler that you have assigned will be destroyed. If you intend to inject some new DOM elements inside the div for which you need to attach event handlers, this attachments should be performed inside the .click handler after inserting the new contents. If the original selector of the event is preserved you may also take a look at the .delegate method to attach the handler.

composer laravel create project

make sure that your composer is up to date. write in the cmd

composer create-project –-prefer-dist laravel/laravel NameOfProject "Version" 

How do you run a single test/spec file in RSpec?

http://github.com/grosser/single_test lets you do stuff like..

rake spec:user          #run spec/model/user_spec.rb (searches for user*_spec.rb)
rake test:users_c       #run test/functional/users_controller_test.rb
rake spec:user:token    #run the first spec in user_spec.rb that matches /token/
rake test:user:token    #run all tests in user_test.rb that match /token/
rake test:last
rake spec:last

Which characters are valid in CSS class names/selectors?

My understanding is that the underscore is technically valid. Check out:

https://developer.mozilla.org/en/underscores_in_class_and_id_names

"...errata to the specification published in early 2001 made underscores legal for the first time."

The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.

What's the source of Error: getaddrinfo EAI_AGAIN?

If you get this error from within a docker container, e.g. when running npm install inside of an alpine container, the cause could be that the network changed since the container was started.

To solve this, just stop and restart the container

docker-compose down
docker-compose up

Source: https://github.com/moby/moby/issues/32106#issuecomment-578725551

Regex: Remove lines containing "help", etc

This is also possible with Notepad++:

  • Go to the search menu, Ctrl + F, and open the Mark tab.
  • Check Bookmark line (if there is no Mark tab update to the current version).

  • Enter your search term and click Mark All

    • All lines containing the search term are bookmarked.
  • Now go to the menu SearchBookmarkRemove Bookmarked lines

  • Done.

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

When creating a new "Google Maps Project", in Android Studio V 1.5.1, the last screen opens the google_maps_api.xml file and displays the screen with instructions as follows:

Resources:

TODO: Before you run your application, you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:

https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r= YOUR SHA-1 + YOUR PACKAGE NAME

You can also add your credentials to an existing key, using this line:
YOUR SHA-1:YOUR PACKAGE NAME

Alternatively, follow the directions here:
https://developers.google.com/maps/documentation/android/start#get-key

Once you have your key (it starts with "AIza"), replace the "google_maps_key" string in this file.
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR GOOGLE MAPS KEY</string>

To get YOUR GOOGLE MAPS KEY just cut and paste the URL link given into your browser and follow the instructions above at the time of creating the new application. The SHA-1 and Package names are already in the link given so you do not need to know them. They will however be in your project in the resources>Values>google_maps_api.xml file which is completed when you follow the instructions on creating the project.

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

your 8080 port is already used by another application 1/ you can try to find out which app is using it, using "netstat -aon" and stop the process; 2/ you can go to server.xml and change from port 8080 to another one (ex: 8081)

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

The solution here that everyone likes seems to very intense... personally I think it's much easier to do something like this:

       var holidays = ["12/24/2012", "12/25/2012", "1/1/2013", 
            "5/27/2013", "7/4/2013", "9/2/2013", "11/28/2013", 
            "11/29/2013", "12/24/2013", "12/25/2013"];

       $( "#requestShipDate" ).datepicker({
            beforeShowDay: function(date){
                show = true;
                if(date.getDay() == 0 || date.getDay() == 6){show = false;}//No Weekends
                for (var i = 0; i < holidays.length; i++) {
                    if (new Date(holidays[i]).toString() == date.toString()) {show = false;}//No Holidays
                }
                var display = [show,'',(show)?'':'No Weekends or Holidays'];//With Fancy hover tooltip!
                return display;
            }
        });

This way your dates are human readable. It's not really that different it just makes more sense to me this way.

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

How to change the value of attribute in appSettings section with Web.config transformation

You want something like:

<appSettings>
  <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/>
  <add key="developmentMode" value="false" xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"/>
</appSettings>

See Also: Web.config Transformation Syntax for Web Application Project Deployment

How to initialize static variables

That's too complex to set in the definition. You can set the definition to null though, and then in the constructor, check it, and if it has not been changed - set it:

private static $dates = null;
public function __construct()
{
    if (is_null(self::$dates)) {  // OR if (!is_array(self::$date))
         self::$dates = array( /* .... */);
    }
}

Invariant Violation: _registerComponent(...): Target container is not a DOM element

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

TypeScript static classes

This is one way:

class SomeClass {
    private static myStaticVariable = "whatever";
    private static __static_ctor = (() => { /* do static constructor stuff :) */ })();
}

__static_ctor here is an immediately invoked function expression. Typescript will output code to call it at the end of the generated class.

Update: For generic types in static constructors, which are no longer allowed to be referenced by static members, you will need an extra step now:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private ___static_ctor = (() => { var someClass:SomeClass<T> ; /* do static constructor stuff :) */ })();
    private static __static_ctor = SomeClass.prototype.___static_ctor();
}

In any case, of course, you could just call the generic type static constructor after the class, such as:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private __static_ctor = (() => { var example: SomeClass<T>; /* do static constructor stuff :) */ })();
}
SomeClass.prototype.__static_ctor();

Just remember to NEVER use this in __static_ctor above (obviously).

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

What does "subject" mean in certificate?

The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).

As RFC 5280 says:

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".

In the context of the article you're linking to, the subject would be the user/owner of the cert.

HTML5 Audio stop function

What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:

<audio id="audioplayer" *ngIf="song?.audio_path">

Then when I want to unload it in code I do this:

this.song = Object.assign({},this.song,{audio_path: null});

When the next song is assigned, the control gets completely recreated from scratch:

this.song = this.songOnDeck;

Pass command parameter to method in ViewModel in WPF?

Just using Data Binding syntax. For example,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

Not only can we use Data Binding to get some data from View Models, but also pass data back to View Models. In CommandParameter, must use ElementName to declare binding source explicitly.

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Wait .5 seconds before continuing code VB.net

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

%20+ high cpu usage + no lag

Private Sub wait(ByVal seconds As Integer)
    For i As Integer = 0 To seconds * 100
        System.Threading.Thread.Sleep(10)
        Application.DoEvents()
    Next
End Sub

%0.1 cpu usage + high lag

Truncate/round whole number in JavaScript?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

Access parent's parent from javascript object

I used something that resembles singleton pattern:

function myclass() = {
    var instance = this;

    this.Days = function() {
        var days = ["Piatek", "Sobota", "Niedziela"];
        return days;
    }

    this.EventTime = function(day, hours, minutes) {
        this.Day = instance.Days()[day];
        this.Hours = hours;
        this.minutes = minutes;
        this.TotalMinutes = day*24*60 + 60*hours + minutes;
    }
}

How to normalize a histogram in MATLAB?

Since 2014b, Matlab has these normalization routines embedded natively in the histogram function (see the help file for the 6 routines this function offers). Here is an example using the PDF normalization (the sum of all the bins is 1).

data = 2*randn(5000,1) + 5;             % generate normal random (m=5, std=2)
h = histogram(data,'Normalization','pdf')   % PDF normalization

The corresponding PDF is

Nbins = h.NumBins;
edges = h.BinEdges; 
x = zeros(1,Nbins);
for counter=1:Nbins
    midPointShift = abs(edges(counter)-edges(counter+1))/2;
    x(counter) = edges(counter)+midPointShift;
end

mu = mean(data);
sigma = std(data);

f = exp(-(x-mu).^2./(2*sigma^2))./(sigma*sqrt(2*pi));

The two together gives

hold on;
plot(x,f,'LineWidth',1.5)

enter image description here

An improvement that might very well be due to the success of the actual question and accepted answer!


EDIT - The use of hist and histc is not recommended now, and histogram should be used instead. Beware that none of the 6 ways of creating bins with this new function will produce the bins hist and histc produce. There is a Matlab script to update former code to fit the way histogram is called (bin edges instead of bin centers - link). By doing so, one can compare the pdf normalization methods of @abcd (trapz and sum) and Matlab (pdf).

The 3 pdf normalization method give nearly identical results (within the range of eps).

TEST:

A = randn(10000,1);
centers = -6:0.5:6;
d = diff(centers)/2;
edges = [centers(1)-d(1), centers(1:end-1)+d, centers(end)+d(end)];
edges(2:end) = edges(2:end)+eps(edges(2:end));

figure;
subplot(2,2,1);
hist(A,centers);
title('HIST not normalized');

subplot(2,2,2);
h = histogram(A,edges);
title('HISTOGRAM not normalized');

subplot(2,2,3)
[counts, centers] = hist(A,centers); %get the count with hist
bar(centers,counts/trapz(centers,counts))
title('HIST with PDF normalization');


subplot(2,2,4)
h = histogram(A,edges,'Normalization','pdf')
title('HISTOGRAM with PDF normalization');

dx = diff(centers(1:2))
normalization_difference_trapz = abs(counts/trapz(centers,counts) - h.Values);
normalization_difference_sum = abs(counts/sum(counts*dx) - h.Values);

max(normalization_difference_trapz)
max(normalization_difference_sum)

enter image description here

The maximum difference between the new PDF normalization and the former one is 5.5511e-17.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.

This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!

  • The Video shows you the JavaFx Sdk download
  • How to set it as a Global Library
  • Set the module-info.java (i prefer the bottom one)

module thisIsTheNameOfYourProject {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens sample;
}

The entire thing took me only 5mins !!!

Not able to start Genymotion device

For me it was related to the lack of virtual resources (Ram and CPU). Go to the virtual box, right click on device -> Setting and increase the value of each resource.

How to concatenate properties from multiple JavaScript objects

ECMAScript 6 has spread syntax. And now you can do this:

_x000D_
_x000D_
const obj1 = { 1: 11, 2: 22 };_x000D_
const obj2 = { 3: 33, 4: 44 };_x000D_
const obj3 = { ...obj1, ...obj2 };_x000D_
_x000D_
console.log(obj3); // {1: 11, 2: 22, 3: 33, 4: 44}
_x000D_
_x000D_
_x000D_

git remove merge commit from history

To Just Remove a Merge Commit

If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows

git rebase --onto <sha of 1> <sha of 2> <blue branch>

And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.

How to protect Excel workbook using VBA?

  1. in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the := notation (see code sample below)

    1. Application.Thisworkbook refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.

Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:

Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)

    If ProtectionMode Then
        MySheet.Protect DrawingObjects:=True, Contents:=True, _
                        AllowSorting:=True, AllowFiltering:=True
    Else
        MySheet.Unprotect
    End If
End Sub

Within the .Protect method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:

Application.Dialogs(xlDialogProtectDocument).Show

Hope that helps

Good luck - MikeD

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

Returning a value even if no result

MySQL has a function to return a value if the result is null. You can use it on a whole query:

SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

Fastest way to flatten / un-flatten nested JSON objects

Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)

Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
        props = Object.keys(data),
        result, p;
    while(p = props.shift()) {
        var m = regex.exec(p),
            target;
        if (m.index) {
            var rest = p.slice(0, m.index);
            if (!(rest in data)) {
                data[rest] = m[2] ? [] : {};
                props.push(rest);
            }
            target = data[rest];
        } else {
            target = result || (result = (m[2] ? [] : {}));
        }
        target[m[2] || m[1]] = data[p];
    }
    return result;
};

It currently uses the data input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf usage performs better than the regex (depends on the regex engine).

See it in action here.

Get value from hidden field using jQuery

If you don't want to assign identifier to the hidden field; you can use name or class with selector like:

$('input[name=hiddenfieldname]').val();

or with assigned class:

$('input.hiddenfieldclass').val();

Can you target <br /> with css?

Why not just use the HR tag? It's made exactly for what you want. Kinda like trying to make a fork for eating soup when there's a spoon right in front of you on the table.

How to call codeigniter controller function from view

Try this one.

Add this code in Your View file

$CI     = & get_instance();
$result = $CI->FindFurnishName($pera);

Add code in Your controller File

public function FindFurnishName($furnish_filter)

{

$FindFurnishName        = $this->index_modal->FindFurnishName($furnish_filter);  
$FindFurnishName_val    = '';
foreach($FindFurnishName as $AllRea)
{
    $FindFurnishName_val  .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');

}

where

  1. FindFurnishName is name of function which is define in Your Controller.
  2. $pera is a option ( as your need).

convert an enum to another type of enum

I wrote a set extension methods a while back that work for several different kinds of Enums. One in particular works for what you are trying to accomplish and handles Enums with the FlagsAttribute as well as Enums with different underlying types.

public static tEnum SetFlags<tEnum>(this Enum e, tEnum flags, bool set, bool typeCheck = true) where tEnum : IComparable
{
    if (typeCheck)
    {
        if (e.GetType() != flags.GetType())
            throw new ArgumentException("Argument is not the same type as this instance.", "flags");
    }

    var flagsUnderlyingType = Enum.GetUnderlyingType(typeof(tEnum));

    var firstNum = Convert.ToUInt32(e);
    var secondNum = Convert.ToUInt32(flags);

    if (set)
        firstNum |= secondNum;

    else
        firstNum &= ~secondNum;

    var newValue = (tEnum)Convert.ChangeType(firstNum, flagsUnderlyingType);

    if (!typeCheck)
    {
        var values = Enum.GetValues(typeof(tEnum));
        var lastValue = (tEnum)values.GetValue(values.Length - 1);

        if (newValue.CompareTo(lastValue) > 0)
            return lastValue;
    }

    return newValue;
}

From there you can add other more specific extension methods.

public static tEnum AddFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
    SetFlags(e, flags, true);
}

public static tEnum RemoveFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
    SetFlags(e, flags, false);
}

This one will change types of Enums like you are trying to do.

public static tEnum ChangeType<tEnum>(this Enum e) where tEnum : IComparable
{
    return SetFlags(e, default(tEnum), true, false);
}

Be warned, though, that you CAN convert between any Enum and any other Enum using this method, even those that do not have flags. For example:

public enum Turtle
{
    None = 0,
    Pink,
    Green,
    Blue,
    Black,
    Yellow
}

[Flags]
public enum WriteAccess : short
{
   None = 0,
   Read = 1,
   Write = 2,
   ReadWrite = 3
}

static void Main(string[] args)
{
    WriteAccess access = WriteAccess.ReadWrite;
    Turtle turtle = access.ChangeType<Turtle>();
}

The variable turtle will have a value of Turtle.Blue.

However, there is safety from undefined Enum values using this method. For instance:

static void Main(string[] args)
{
    Turtle turtle = Turtle.Yellow;
    WriteAccess access = turtle.ChangeType<WriteAccess>();
}

In this case, access will be set to WriteAccess.ReadWrite, since the WriteAccess Enum has a maximum value of 3.

Another side effect of mixing Enums with the FlagsAttribute and those without it is that the conversion process will not result in a 1 to 1 match between their values.

public enum Letters
{
    None = 0,
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

[Flags]
public enum Flavors
{
    None = 0,
    Cherry = 1,
    Grape = 2,
    Orange = 4,
    Peach = 8
}

static void Main(string[] args)
{
    Flavors flavors = Flavors.Peach;
    Letters letters = flavors.ChangeType<Letters>();
}

In this case, letters will have a value of Letters.H instead of Letters.D, since the backing value of Flavors.Peach is 8. Also, a conversion from Flavors.Cherry | Flavors.Grape to Letters would yield Letters.C, which can seem unintuitive.

PHP Redirect with POST data

/**
  * Redirect with POST data.
  *
  * @param string $url URL.
  * @param array $post_data POST data. Example: ['foo' => 'var', 'id' => 123]
  * @param array $headers Optional. Extra headers to send.
  */
public function redirect_post($url, array $data, array $headers = null) {
  $params = [
    'http' => [
      'method' => 'POST',
      'content' => http_build_query($data)
    ]
  ];

  if (!is_null($headers)) {
    $params['http']['header'] = '';
    foreach ($headers as $k => $v) {
      $params['http']['header'] .= "$k: $v\n";
    }
  }

  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);

  if ($fp) {
    echo @stream_get_contents($fp);
    die();
  } else {
    // Error
    throw new Exception("Error loading '$url', $php_errormsg");
  }
}

import .css file into .less file

If you just want to import a CSS-File as a Reference (e.g. to use the classes in Mixins) but not include the whole CSS file in the result you can use @import (less,reference) "reference.css";:

my.less

 @import (less,reference) "reference.css";
 .my-class{
     background-color:black;
     .reference-class;
     color:blue;
 }

reference.css

.reference-class{
    border: 1px solid red;
}

*Result (my.css) with lessc my.less out/my.css *

.my-class {
  background-color: black;
  border: 1px solid red;
  color: blue;
}

I'm using lessc 2.5.3

Enable/Disable Anchor Tags using AngularJS

Have you tried using lazy evaluation of expressions like disabled || someAction()?

Lets assume I defined something like so in my controller:

$scope.disabled = true;

Then I can disabling a link and apply inline styles like so:

<a data-ng-click="disabled || (GoTo('#/employer/'))" data-ng-style="disabled && { 'background-color': 'rgba(99, 99, 99, 0.5)', }">Higher Level</a>

Or better still disable a link and apply a class like so:

<a data-ng-click="disabled || (GoTo('#/employer/'))" data-ng-class="{ disabled: disabled }">Higher Level</a>

Note: that you will have a class="disabled" applied to DOM element by that statement.

At this stage you just need to handle what you action GoTo() will do. In my case its as simple as redirect to associated state:

$scope.GoTo = function (state) {
    if (state != undefined && state.length > 0) {
        $window.location.hash = state;
    }
};

Rather than being limited by ngDisabled you are limited by what you decide to do.

With this technique I successfully applied permission level checking to enable or disable user access to certain part of my module.

Simple plunker to demonstrate the point

Bootstrap 3 Navbar Collapse

The big difference between Bootstrap 2 and Bootstrap 3 is that Bootstrap 3 is "mobile first".

That means the default styles are designed for mobile devices and in the case of Navbars, that means it's "collapsed" by default and "expands" when it reaches a certain minimum size.

Bootstrap 3's site actually has a "hint" as to what to do: http://getbootstrap.com/components/#navbar

Customize the collapsing point

Depending on the content in your navbar, you might need to change the point at which your navbar switches between collapsed and horizontal mode. Customize the @grid-float-breakpoint variable or add your own media query.

If you're going to re-compile your LESS, you'll find the noted LESS variable in the variables.less file. It's currently set to "expand" @media (min-width: 768px) which is a "small screen" (ie. a tablet) by Bootstrap 3 terms.

@grid-float-breakpoint: @screen-tablet;

If you want to keep the collapsed a little longer you can adjust it like such:

@grid-float-breakpoint: @screen-desktop; (992px break-point)

or expand sooner

@grid-float-breakpoint: @screen-phone (480px break-point)

If you want to have it expand later, and not deal with re-compiling the LESS, you'll have to overwrite the styles that get applied at the 768px media query and have them return to the previous value. Then re-add them at the appropriate time.

I'm not sure if there's a better way to do it. Recompiling the Bootstrap LESS to your needs is the best (easiest) way. Otherwise, you'll have to find all the CSS media queries that affect your Navbar, overwrite them to default styles @ the 768px width and then revert them back at a higher min-width.

Recompiling the LESS will do all that magic for you just by changing the variable. Which is pretty much the point of LESS/SASS pre-compilers. =)

(note, I did look them all up, it's about 100 lines of code, which is annoy enough for me to drop the idea and just re-compile Bootstrap for a given project and avoid messing something up by accident)

I hope that helps!

Cheers!

String.Format not work in TypeScript

If you are using NodeJS, you can use the build-in util function:

import * as util from "util";
util.format('My string: %s', 'foo');

Document can be found here: https://nodejs.org/api/util.html#util_util_format_format_args

Eclipse jump to closing brace

To select content use Alt + Shift + Up arrow

To select content up to the next wrapping block press this shortcut again

To go back one step press Alt + Shift + Down arrow. This is also a useful shortcut when you need to select content in a complex expression and do not want to miss something.

How to add icon inside EditText view in Android ?

You can set drawableLeft in the XML as suggested by marcos, but you might also want to set it programmatically - for example in response to an event. To do this use the method setCompoundDrawablesWithIntrincisBounds(int, int, int, int):

EditText editText = findViewById(R.id.myEditText);

// Set drawables for left, top, right, and bottom - send 0 for nothing
editTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

ShowAllData method of Worksheet class failed

The error ShowAllData method of Worksheet class failed usually occurs when you try to remove an applied filter when there is not one applied.

I am not certain if you are trying to remove the whole AutoFilter, or just remove any applied filter, but there are different approaches for each.

To remove an applied filter but leave AutoFilter on:

If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
End If

The rationale behind the above code is to test that there is an AutoFilter or whether a filter has been applied (this will also remove advanced filters).

To completely remove the AutoFilter:

ActiveSheet.AutoFilterMode = False

In the above case, you are simply disabling the AutoFilter completely.

How to Delete Session Cookie?

A session cookie is just a normal cookie without an expiration date. Those are handled by the browser to be valid until the window is closed or program is quit.

But if the cookie is a httpOnly cookie (a cookie with the httpOnly parameter set), you cannot read, change or delete it from outside of HTTP (meaning it must be changed on the server).

Why is String immutable in Java?

Most important reason according to this article on DZone:

String Constant Pool ... If string is mutable, changing the string with one reference will lead to the wrong value for the other references.

Security

String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. ...

Hope it will help you.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

This is example:

$.ajax({
  url: "test.html",
  async: false
}).done(function(data) {
   // Todo something..
}).fail(function(xhr)  {
   // Todo something..
});

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

How do I get into a Docker container's shell?

GOINSIDE SOLUTION

install goinside command line tool with:

sudo npm install -g goinside

and go inside a docker container with a proper terminal size with:

goinside docker_container_name

old answer

We've put this snippet in ~/.profile:

goinside(){
    docker exec -it $1 bash -c "stty cols $COLUMNS rows $LINES && bash";
}
export -f goinside

Not only does this make everyone able to get inside a running container with:

goinside containername

It also solves a long lived problem about fixed Docker container terminal sizes. Which is very annoying if you face it.

Also if you follow the link you'll have command completion for your docker container names too.

Getting the name of a variable as a string

def name(**variables):
    return [x for x in variables]

It's used like this:

name(variable=variable)

How to use "like" and "not like" in SQL MSAccess for the same field?

If you're doing it in VBA (and not in a query) then: where field like "AA" and field not like "BB" then would not work.

You'd have to use: where field like "AA" and field like "BB" = false then

How to force the input date format to dd/mm/yyyy?

To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow

<input id="txtDay" type="text" placeholder="DD" />

<input id="txtMonth" type="text" placeholder="MM" />

<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>


  function validateDate() {
    var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);

    if (date == "Invalid Date") {
        alert("jnvalid date");

    }
}

Ordering issue with date values when creating pivot tables

You need to select the entire column where you have the dates, so click the "text to columns" button, and select delimited > uncheck all the boxes and go until you click the button finish.

This will make the cell format and then the values will be readed as date.

Hope it will helped.

Recommended method for escaping HTML in Java

On android (API 16 or greater) you can:

Html.escapeHtml(textToScape);

or for lower API:

TextUtils.htmlEncode(textToScape);

How to convert an xml string to a dictionary?

Here's a link to an ActiveState solution - and the code in case it disappears again.

==================================================
xmlreader.py:
==================================================
from xml.dom.minidom import parse


class NotTextNodeError:
    pass


def getTextFromNode(node):
    """
    scans through all children of node and gathers the
    text. if node has non-text child-nodes, then
    NotTextNodeError is raised.
    """
    t = ""
    for n in node.childNodes:
    if n.nodeType == n.TEXT_NODE:
        t += n.nodeValue
    else:
        raise NotTextNodeError
    return t


def nodeToDic(node):
    """
    nodeToDic() scans through the children of node and makes a
    dictionary from the content.
    three cases are differentiated:
    - if the node contains no other nodes, it is a text-node
    and {nodeName:text} is merged into the dictionary.
    - if the node has the attribute "method" set to "true",
    then it's children will be appended to a list and this
    list is merged to the dictionary in the form: {nodeName:list}.
    - else, nodeToDic() will call itself recursively on
    the nodes children (merging {nodeName:nodeToDic()} to
    the dictionary).
    """
    dic = {} 
    for n in node.childNodes:
    if n.nodeType != n.ELEMENT_NODE:
        continue
    if n.getAttribute("multiple") == "true":
        # node with multiple children:
        # put them in a list
        l = []
        for c in n.childNodes:
            if c.nodeType != n.ELEMENT_NODE:
            continue
        l.append(nodeToDic(c))
            dic.update({n.nodeName:l})
        continue

    try:
        text = getTextFromNode(n)
    except NotTextNodeError:
            # 'normal' node
            dic.update({n.nodeName:nodeToDic(n)})
            continue

        # text node
        dic.update({n.nodeName:text})
    continue
    return dic


def readConfig(filename):
    dom = parse(filename)
    return nodeToDic(dom)





def test():
    dic = readConfig("sample.xml")

    print dic["Config"]["Name"]
    print
    for item in dic["Config"]["Items"]:
    print "Item's Name:", item["Name"]
    print "Item's Value:", item["Value"]

test()



==================================================
sample.xml:
==================================================
<?xml version="1.0" encoding="UTF-8"?>

<Config>
    <Name>My Config File</Name>

    <Items multiple="true">
    <Item>
        <Name>First Item</Name>
        <Value>Value 1</Value>
    </Item>
    <Item>
        <Name>Second Item</Name>
        <Value>Value 2</Value>
    </Item>
    </Items>

</Config>



==================================================
output:
==================================================
My Config File

Item's Name: First Item
Item's Value: Value 1
Item's Name: Second Item
Item's Value: Value 2

Concat all strings inside a List<string> using LINQ

I think that if you define the logic in an extension method the code will be much more readable:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

Import regular CSS file in SCSS file?

It is now possible using:

@import 'CSS:directory/filename.css';